UNPKG

1.63 kBJavaScriptView Raw
1import { addLeadingZeros } from "./_lib/addLeadingZeros.js";
2import { isValid } from "./isValid.js";
3import { toDate } from "./toDate.js";
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 * @param date - The original date
32 *
33 * @returns The formatted date string
34 *
35 * @throws `date` must not be Invalid Date
36 *
37 * @example
38 * // Represent 18 September 2019 in RFC 7231 format:
39 * const result = formatRFC7231(new Date(2019, 8, 18, 19, 0, 52))
40 * //=> 'Wed, 18 Sep 2019 19:00:52 GMT'
41 */
42export function formatRFC7231(date) {
43 const _date = toDate(date);
44
45 if (!isValid(_date)) {
46 throw new RangeError("Invalid time value");
47 }
48
49 const dayName = days[_date.getUTCDay()];
50 const dayOfMonth = addLeadingZeros(_date.getUTCDate(), 2);
51 const monthName = months[_date.getUTCMonth()];
52 const year = _date.getUTCFullYear();
53
54 const hour = addLeadingZeros(_date.getUTCHours(), 2);
55 const minute = addLeadingZeros(_date.getUTCMinutes(), 2);
56 const second = addLeadingZeros(_date.getUTCSeconds(), 2);
57
58 // Result variables.
59 return `${dayName}, ${dayOfMonth} ${monthName} ${year} ${hour}:${minute}:${second} GMT`;
60}
61
62// Fallback for modularized imports:
63export default formatRFC7231;