UNPKG

1.82 kBJavaScriptView Raw
1import { isValid } from "./isValid.mjs";
2import { toDate } from "./toDate.mjs";
3import { addLeadingZeros } from "./_lib/addLeadingZeros.mjs";
4
5const days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
6
7const 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/**
23 * @name formatRFC7231
24 * @category Common Helpers
25 * @summary Format the date according to the RFC 7231 standard (https://tools.ietf.org/html/rfc7231#section-7.1.1.1).
26 *
27 * @description
28 * Return the formatted date string in RFC 7231 format.
29 * The result will always be in UTC timezone.
30 *
31 * @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).
32 *
33 * @param date - The original date
34 *
35 * @returns The formatted date string
36 *
37 * @throws `date` must not be Invalid Date
38 *
39 * @example
40 * // Represent 18 September 2019 in RFC 7231 format:
41 * const result = formatRFC7231(new Date(2019, 8, 18, 19, 0, 52))
42 * //=> 'Wed, 18 Sep 2019 19:00:52 GMT'
43 */
44export function formatRFC7231(date) {
45 const _date = toDate(date);
46
47 if (!isValid(_date)) {
48 throw new RangeError("Invalid time value");
49 }
50
51 const dayName = days[_date.getUTCDay()];
52 const dayOfMonth = addLeadingZeros(_date.getUTCDate(), 2);
53 const monthName = months[_date.getUTCMonth()];
54 const year = _date.getUTCFullYear();
55
56 const hour = addLeadingZeros(_date.getUTCHours(), 2);
57 const minute = addLeadingZeros(_date.getUTCMinutes(), 2);
58 const second = addLeadingZeros(_date.getUTCSeconds(), 2);
59
60 // Result variables.
61 return `${dayName}, ${dayOfMonth} ${monthName} ${year} ${hour}:${minute}:${second} GMT`;
62}
63
64// Fallback for modularized imports:
65export default formatRFC7231;