Open History to see the last commit
1const TIME_FORMATTER = new Intl.DateTimeFormat(undefined, { hour: "numeric", minute: "2-digit" });
2const DATE_FORMATTER = new Intl.DateTimeFormat(undefined, { month: "numeric", day: "numeric" });
3const DATE_WITH_YEAR_FORMATTER = new Intl.DateTimeFormat(undefined, {
4 month: "numeric",
5 day: "numeric",
6 year: "numeric",
7});
8
9/** Time only for today's messages; older ones lead with the day and month. */
10export function formatMessageTimestamp(
11 input: string,
12 nowMs: number = Date.now(),
13 timeFormatter: Intl.DateTimeFormat = TIME_FORMATTER,
14): string {
15 const timestamp = Date.parse(input);
16 if (Number.isNaN(timestamp)) return "";
17 const date = new Date(timestamp);
18 const now = new Date(nowMs);
19 const time = timeFormatter.format(date);
20 if (date.toDateString() === now.toDateString()) return time;
21 const sameYear = date.getFullYear() === now.getFullYear();
22 return `${(sameYear ? DATE_FORMATTER : DATE_WITH_YEAR_FORMATTER).format(date)} ${time}`;
23}
24
25/** `is24Hour` overrides the locale's hour cycle with the system clock preference when known. */
26export function createMessageTimeFormatter(is24Hour: boolean | undefined, locale?: string) {
27 const timeFormatter = new Intl.DateTimeFormat(locale, {
28 hour: "numeric",
29 minute: "2-digit",
30 ...(is24Hour === undefined ? {} : { hourCycle: is24Hour ? "h23" : "h12" }),
31 });
32 return (input: string, nowMs?: number): string =>
33 formatMessageTimestamp(input, nowMs, timeFormatter);
34}