-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdate-time.ts
91 lines (77 loc) · 2.14 KB
/
date-time.ts
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
// file: src/lib/date-time.ts
const defaultOptionsBriefDateFormat: Intl.ResolvedDateTimeFormatOptions = {
locale: 'en-GB',
timeZone: 'UTC',
numberingSystem: 'latn',
calendar: 'gregory',
hour12: false,
};
export type FormatFn = (
epochTimestamp: number
) => [local: string, utcIso: string];
function makeNoteDateFormat({
locale,
timeZone,
hour12,
} = defaultOptionsBriefDateFormat) {
const display = Intl.DateTimeFormat(locale, {
timeZone,
hour12,
dateStyle: 'medium',
timeStyle: 'short',
});
const format: FormatFn = function format(epochTimestamp: number) {
const dateTime = new Date(epochTimestamp);
return [display.format(dateTime), dateTime.toISOString()];
};
return format;
}
function makeBriefDateFormat({
locale,
timeZone,
hour12,
} = defaultOptionsBriefDateFormat) {
const dateOnly = Intl.DateTimeFormat(locale, {
timeZone,
hour12,
dateStyle: 'short',
});
const timeOnly = Intl.DateTimeFormat(locale, {
timeZone,
hour12,
timeStyle: 'short',
});
let today = new Date();
const format: FormatFn = function format(
epochTimestamp: number,
resetToday = false
) {
if (resetToday) today = new Date();
const dateTime = new Date(epochTimestamp);
const display =
dateTime.getDate() === today.getDate() &&
dateTime.getMonth() === today.getMonth() &&
dateTime.getFullYear() === today.getFullYear()
? timeOnly.format(dateTime)
: dateOnly.format(dateTime);
return [display, dateTime.toISOString()];
};
return format;
}
function localizeFormat(
format: FormatFn,
timeAncestor: HTMLElement | undefined
): void {
if (!(timeAncestor instanceof HTMLElement))
throw new Error('Unsuitable ancestor element');
const time = timeAncestor.querySelector('time');
if (!(time instanceof HTMLTimeElement))
throw new Error('Unable to locate time element under specified ancestor');
const current = time.textContent;
if (!current) return;
// i.e. nothing to do (CSR waiting for async content)
const epochTimestamp = Date.parse(time.dateTime);
const [local] = format(epochTimestamp);
if (current !== local) time.textContent = local;
}
export { localizeFormat, makeBriefDateFormat, makeNoteDateFormat };