MCPcopy
hub / github.com/date-fns/date-fns / formatISO

Function formatISO

pkgs/core/src/formatISO/index.ts:46–107  ·  view source on GitHub ↗
(
  date: DateArg<Date> & {},
  options?: FormatISOOptions,
)

Source from the content-addressed store, hash-verified

44 * //=> '19:00:52Z'
45 */
46export function formatISO(
47 date: DateArg<Date> & {},
48 options?: FormatISOOptions,
49): string {
50 const date_ = toDate(date, options?.in);
51
52 if (isNaN(+date_)) {
53 throw new RangeError("Invalid time value");
54 }
55
56 const format = options?.format ?? "extended";
57 const representation = options?.representation ?? "complete";
58
59 let result = "";
60 let tzOffset = "";
61
62 const dateDelimiter = format === "extended" ? "-" : "";
63 const timeDelimiter = format === "extended" ? ":" : "";
64
65 // Representation is either 'date' or 'complete'
66 if (representation !== "time") {
67 const day = addLeadingZeros(date_.getDate(), 2);
68 const month = addLeadingZeros(date_.getMonth() + 1, 2);
69 const year = addLeadingZeros(date_.getFullYear(), 4);
70
71 // yyyyMMdd or yyyy-MM-dd.
72 result = `${year}${dateDelimiter}${month}${dateDelimiter}${day}`;
73 }
74
75 // Representation is either 'time' or 'complete'
76 if (representation !== "date") {
77 // Add the timezone.
78 const offset = date_.getTimezoneOffset();
79
80 if (offset !== 0) {
81 const absoluteOffset = Math.abs(offset);
82 const hourOffset = addLeadingZeros(Math.trunc(absoluteOffset / 60), 2);
83 const minuteOffset = addLeadingZeros(absoluteOffset % 60, 2);
84 // If less than 0, the sign is +, because it is ahead of time.
85 const sign = offset < 0 ? "+" : "-";
86
87 tzOffset = `${sign}${hourOffset}:${minuteOffset}`;
88 } else {
89 tzOffset = "Z";
90 }
91
92 const hour = addLeadingZeros(date_.getHours(), 2);
93 const minute = addLeadingZeros(date_.getMinutes(), 2);
94 const second = addLeadingZeros(date_.getSeconds(), 2);
95
96 // If there's also date, separate it with time with 'T'
97 const separator = result === "" ? "" : "T";
98
99 // Creates a time string consisting of hour, minute, and second, separated by delimiters, if defined.
100 const time = [hour, minute, second].join(timeDelimiter);
101
102 // HHmmss or HH:mm:ss.
103 result = `${result}${separator}${time}${tzOffset}`;

Callers 2

india.tsFile · 0.90
test.tsFile · 0.90

Calls 3

toDateFunction · 0.90
addLeadingZerosFunction · 0.90
getTimezoneOffsetMethod · 0.45

Tested by

no test coverage detected