1 | import { addLeadingZeros } from "./_lib/addLeadingZeros.js";
|
2 | import { isValid } from "./isValid.js";
|
3 | import { toDate } from "./toDate.js";
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 | export 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 |
|
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 |
|
81 | export default formatRFC3339;
|