Open History to see the last commit
1// Formatters pin the default zone when built, and Hermes keeps Date's local offset until a cold
2// start (react/react-native#59131), so formatting and day checks follow the zone Intl reports.
3function buildFormatters(timeZone: string, locale?: string, is24Hour?: boolean) {
4 return {
5 timeZone,
6 time: new Intl.DateTimeFormat(locale, {
7 hour: "numeric",
8 minute: "2-digit",
9 timeZone,
10 ...(is24Hour === undefined ? {} : { hourCycle: is24Hour ? "h23" : "h12" }),
11 }),
12 date: new Intl.DateTimeFormat(locale, { month: "numeric", day: "numeric", timeZone }),
13 dateWithYear: new Intl.DateTimeFormat(locale, {
14 month: "numeric",
15 day: "numeric",
16 year: "numeric",
17 timeZone,
18 }),
19 year: new Intl.DateTimeFormat(locale, { year: "numeric", timeZone }),
20 };
21}
22
23// Reading the zone builds a formatter (tens of µs), so feed rows share one read per second.
24const ZONE_RECHECK_MS = 1_000;
25let formatters: ReturnType<typeof buildFormatters> | null = null;
26let zoneCheckedAt = 0;
27function currentFormatters() {
28 const now = Date.now();
29 if (formatters && Math.abs(now - zoneCheckedAt) < ZONE_RECHECK_MS) return formatters;
30 zoneCheckedAt = now;
31 const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
32 if (!formatters || formatters.timeZone !== timeZone) formatters = buildFormatters(timeZone);
33 return formatters;
34}
35
36/** Time only for today's messages; older ones lead with the day and month. */
37export function formatMessageTimestamp(
38 input: string,
39 nowMs: number = Date.now(),
40 f: ReturnType<typeof buildFormatters> = currentFormatters(),
41): string {
42 const timestamp = Date.parse(input);
43 if (Number.isNaN(timestamp)) return "";
44 const time = f.time.format(timestamp);
45 const dateWithYear = f.dateWithYear.format(timestamp);
46 if (dateWithYear === f.dateWithYear.format(nowMs)) return time;
47 const sameYear = f.year.format(timestamp) === f.year.format(nowMs);
48 return `${sameYear ? f.date.format(timestamp) : dateWithYear} ${time}`;
49}
50
51/** `is24Hour` overrides the locale's hour cycle with the system clock preference when known. */
52export function createMessageTimeFormatter(is24Hour: boolean | undefined, locale?: string) {
53 let cached: ReturnType<typeof buildFormatters> | null = null;
54 return (input: string, nowMs?: number): string => {
55 const { timeZone } = currentFormatters();
56 if (cached?.timeZone !== timeZone) cached = buildFormatters(timeZone, locale, is24Hour);
57 return formatMessageTimestamp(input, nowMs, cached);
58 };
59}