formatRFC7231.js 1.6 KB

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