formatRFC7231.mjs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { isValid } from "./isValid.mjs";
  2. import { toDate } from "./toDate.mjs";
  3. import { addLeadingZeros } from "./_lib/addLeadingZeros.mjs";
  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. * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
  29. *
  30. * @param date - The original date
  31. *
  32. * @returns The formatted date string
  33. *
  34. * @throws `date` must not be Invalid Date
  35. *
  36. * @example
  37. * // Represent 18 September 2019 in RFC 7231 format:
  38. * const result = formatRFC7231(new Date(2019, 8, 18, 19, 0, 52))
  39. * //=> 'Wed, 18 Sep 2019 19:00:52 GMT'
  40. */
  41. export function formatRFC7231(date) {
  42. const _date = toDate(date);
  43. if (!isValid(_date)) {
  44. throw new RangeError("Invalid time value");
  45. }
  46. const dayName = days[_date.getUTCDay()];
  47. const dayOfMonth = addLeadingZeros(_date.getUTCDate(), 2);
  48. const monthName = months[_date.getUTCMonth()];
  49. const year = _date.getUTCFullYear();
  50. const hour = addLeadingZeros(_date.getUTCHours(), 2);
  51. const minute = addLeadingZeros(_date.getUTCMinutes(), 2);
  52. const second = addLeadingZeros(_date.getUTCSeconds(), 2);
  53. // Result variables.
  54. return `${dayName}, ${dayOfMonth} ${monthName} ${year} ${hour}:${minute}:${second} GMT`;
  55. }
  56. // Fallback for modularized imports:
  57. export default formatRFC7231;