Repository navigation
Expand file tree
/
Copy pathapiDates.ts
More file actions
103 lines (83 loc) · 3.95 KB
/
Copy pathapiDates.ts
File metadata and controls
103 lines (83 loc) · 3.95 KB
1
2
3
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/** Parse API timestamps; datetimes without an explicit timezone are interpreted as UTC. */
export function parseApiTimestamp(value: unknown): number | null {
if (typeof value === "boolean" || value === null || value === undefined) return null;
const stringValue = typeof value === "string" ? value.trim() : null;
if (stringValue === "") return null;
const numeric = typeof value === "number"
? value
: stringValue !== null && /^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i.test(stringValue)
? Number(stringValue) : null;
if (numeric !== null && Number.isFinite(numeric)) {
const secondsAsMilliseconds = numeric * 1_000;
// Prefer seconds below the legacy threshold, falling back to milliseconds when out of range.
const preferSeconds = Math.abs(numeric) < 1_000_000_000_000;
const primary = preferSeconds ? secondsAsMilliseconds : numeric;
const fallback = preferSeconds ? numeric : secondsAsMilliseconds;
return isValidDateMilliseconds(primary)
? primary
: isValidDateMilliseconds(fallback) ? fallback : null;
}
return stringValue === null ? null : parseStrictIsoTimestamp(stringValue);
}
function parseStrictIsoTimestamp(value: string): number | null {
const match = /^(\d{4})-(\d{2})-(\d{2})(?:([Tt ])(\d{2}):(\d{2})(?::(\d{2})(\.\d+)?)?(Z|z|([+-])(\d{2}):(\d{2}))?)?$/.exec(value);
if (match === null) return null;
const year = Number(match[1]);
const month = Number(match[2]);
const day = Number(match[3]);
if (!isValidCalendarDate(year, month, day)) return null;
if (match[4] === undefined) {
return createUtcMilliseconds(year, month, day, 0, 0, 0, 0);
}
const hour = Number(match[5]);
const minute = Number(match[6]);
const second = Number(match[7] ?? 0);
if (hour > 23 || minute > 59 || second > 59) return null;
const fractionDigits = match[8]?.slice(1) ?? "";
const milliseconds = Number((fractionDigits + "000").slice(0, 3));
let timestamp = createUtcMilliseconds(year, month, day, hour, minute, second, milliseconds);
if (match[10] !== undefined) {
const offsetHour = Number(match[11]);
const offsetMinute = Number(match[12]);
if (offsetHour > 14 || offsetMinute > 59 || (offsetHour === 14 && offsetMinute !== 0)) return null;
const offsetMilliseconds = (offsetHour * 60 + offsetMinute) * 60_000;
timestamp += match[10] === "+" ? -offsetMilliseconds : offsetMilliseconds;
}
return isValidDateMilliseconds(timestamp) ? timestamp : null;
}
function isValidCalendarDate(year: number, month: number, day: number): boolean {
if (month < 1 || month > 12 || day < 1) return false;
const daysInMonth = [31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
return day <= daysInMonth[month - 1];
}
function createUtcMilliseconds(
year: number,
month: number,
day: number,
hour: number,
minute: number,
second: number,
milliseconds: number,
): number {
const date = new Date(0);
date.setUTCFullYear(year, month - 1, day);
date.setUTCHours(hour, minute, second, milliseconds);
return date.getTime();
}
function isLeapYear(year: number): boolean {
return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
}
function isValidDateMilliseconds(milliseconds: number): boolean {
if (!Number.isFinite(milliseconds) || Math.abs(milliseconds) > 8.64e15) return false;
const year = new Date(milliseconds).getUTCFullYear();
return year >= 0 && year <= 9_999;
}
/** Format a parsed timestamp for spreadsheet use, preserving millisecond precision in UTC. */
export function formatUtcDateTime(milliseconds: number | null | undefined): string {
if (milliseconds === null || milliseconds === undefined || !isValidDateMilliseconds(milliseconds)) return "";
return new Date(milliseconds).toISOString().replace("T", " ").replace(/(?:\.000)?Z$/, "");
}
/** API timestamps can be Unix seconds, Unix milliseconds, or ISO dates and datetimes. */
export function formatApiDateTime(value: unknown): string {
return formatUtcDateTime(parseApiTimestamp(value));
}