UNPKG

2.53 kBJavaScriptView Raw
1import { addLeadingZeros } from "./_lib/addLeadingZeros.js";
2import { isValid } from "./isValid.js";
3import { toDate } from "./toDate.js";
4
5/**
6 * The {@link formatRFC3339} function options.
7 */
8
9/**
10 * @name formatRFC3339
11 * @category Common Helpers
12 * @summary Format the date according to the RFC 3339 standard (https://tools.ietf.org/html/rfc3339#section-5.6).
13 *
14 * @description
15 * Return the formatted date string in RFC 3339 format. Options may be passed to control the parts and notations of the date.
16 *
17 * @param date - The original date
18 * @param options - An object with options.
19 *
20 * @returns The formatted date string
21 *
22 * @throws `date` must not be Invalid Date
23 *
24 * @example
25 * // Represent 18 September 2019 in RFC 3339 format:
26 * formatRFC3339(new Date(2019, 8, 18, 19, 0, 52))
27 * //=> '2019-09-18T19:00:52Z'
28 *
29 * @example
30 * // Represent 18 September 2019 in RFC 3339 format, 3 digits of second fraction
31 * formatRFC3339(new Date(2019, 8, 18, 19, 0, 52, 234), {
32 * fractionDigits: 3
33 * })
34 * //=> '2019-09-18T19:00:52.234Z'
35 */
36export function formatRFC3339(date, options) {
37 const date_ = toDate(date, options?.in);
38
39 if (!isValid(date_)) {
40 throw new RangeError("Invalid time value");
41 }
42
43 const fractionDigits = options?.fractionDigits ?? 0;
44
45 const day = addLeadingZeros(date_.getDate(), 2);
46 const month = addLeadingZeros(date_.getMonth() + 1, 2);
47 const year = date_.getFullYear();
48
49 const hour = addLeadingZeros(date_.getHours(), 2);
50 const minute = addLeadingZeros(date_.getMinutes(), 2);
51 const second = addLeadingZeros(date_.getSeconds(), 2);
52
53 let fractionalSecond = "";
54 if (fractionDigits > 0) {
55 const milliseconds = date_.getMilliseconds();
56 const fractionalSeconds = Math.trunc(
57 milliseconds * Math.pow(10, fractionDigits - 3),
58 );
59 fractionalSecond = "." + addLeadingZeros(fractionalSeconds, fractionDigits);
60 }
61
62 let offset = "";
63 const tzOffset = date_.getTimezoneOffset();
64
65 if (tzOffset !== 0) {
66 const absoluteOffset = Math.abs(tzOffset);
67 const hourOffset = addLeadingZeros(Math.trunc(absoluteOffset / 60), 2);
68 const minuteOffset = addLeadingZeros(absoluteOffset % 60, 2);
69 // If less than 0, the sign is +, because it is ahead of time.
70 const sign = tzOffset < 0 ? "+" : "-";
71
72 offset = `${sign}${hourOffset}:${minuteOffset}`;
73 } else {
74 offset = "Z";
75 }
76
77 return `${year}-${month}-${day}T${hour}:${minute}:${second}${fractionalSecond}${offset}`;
78}
79
80// Fallback for modularized imports:
81export default formatRFC3339;