formatRFC7231.cjs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. "use strict";
  2. exports.formatRFC7231 = formatRFC7231;
  3. var _index = require("./_lib/addLeadingZeros.cjs");
  4. var _index2 = require("./isValid.cjs");
  5. var _index3 = require("./toDate.cjs");
  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. * @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. function formatRFC7231(date) {
  42. const _date = (0, _index3.toDate)(date);
  43. if (!(0, _index2.isValid)(_date)) {
  44. throw new RangeError("Invalid time value");
  45. }
  46. const dayName = days[_date.getUTCDay()];
  47. const dayOfMonth = (0, _index.addLeadingZeros)(_date.getUTCDate(), 2);
  48. const monthName = months[_date.getUTCMonth()];
  49. const year = _date.getUTCFullYear();
  50. const hour = (0, _index.addLeadingZeros)(_date.getUTCHours(), 2);
  51. const minute = (0, _index.addLeadingZeros)(_date.getUTCMinutes(), 2);
  52. const second = (0, _index.addLeadingZeros)(_date.getUTCSeconds(), 2);
  53. // Result variables.
  54. return `${dayName}, ${dayOfMonth} ${monthName} ${year} ${hour}:${minute}:${second} GMT`;
  55. }