index.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import toDate from "../toDate/index.js";
  2. import isValid from "../isValid/index.js";
  3. import addLeadingZeros from "../_lib/addLeadingZeros/index.js";
  4. var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
  5. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  6. /**
  7. * @name formatRFC7231
  8. * @category Common Helpers
  9. * @summary Format the date according to the RFC 7231 standard (https://tools.ietf.org/html/rfc7231#section-7.1.1.1).
  10. *
  11. * @description
  12. * Return the formatted date string in RFC 7231 format.
  13. * The result will always be in UTC timezone.
  14. *
  15. * @param {Date|Number} date - the original date
  16. * @returns {String} the formatted date string
  17. * @throws {TypeError} 1 argument required
  18. * @throws {RangeError} `date` must not be Invalid Date
  19. *
  20. * @example
  21. * // Represent 18 September 2019 in RFC 7231 format:
  22. * const result = formatRFC7231(new Date(2019, 8, 18, 19, 0, 52))
  23. * //=> 'Wed, 18 Sep 2019 19:00:52 GMT'
  24. */
  25. export default function formatRFC7231(dirtyDate) {
  26. if (arguments.length < 1) {
  27. throw new TypeError("1 arguments required, but only ".concat(arguments.length, " present"));
  28. }
  29. var originalDate = toDate(dirtyDate);
  30. if (!isValid(originalDate)) {
  31. throw new RangeError('Invalid time value');
  32. }
  33. var dayName = days[originalDate.getUTCDay()];
  34. var dayOfMonth = addLeadingZeros(originalDate.getUTCDate(), 2);
  35. var monthName = months[originalDate.getUTCMonth()];
  36. var year = originalDate.getUTCFullYear();
  37. var hour = addLeadingZeros(originalDate.getUTCHours(), 2);
  38. var minute = addLeadingZeros(originalDate.getUTCMinutes(), 2);
  39. var second = addLeadingZeros(originalDate.getUTCSeconds(), 2); // Result variables.
  40. return "".concat(dayName, ", ").concat(dayOfMonth, " ").concat(monthName, " ").concat(year, " ").concat(hour, ":").concat(minute, ":").concat(second, " GMT");
  41. }