formatRFC7231.js 1.8 KB

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