Skip to content
Source
Sign inSign up

messageTimestamp.ts

19 lines908 Bytes

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(input: string, nowMs: number = Date.now()): string {
11 const timestamp = Date.parse(input);
12 if (Number.isNaN(timestamp)) return "";
13 const date = new Date(timestamp);
14 const now = new Date(nowMs);
15 const time = TIME_FORMATTER.format(date);
16 if (date.toDateString() === now.toDateString()) return time;
17 const sameYear = date.getFullYear() === now.getFullYear();
18 return `${(sameYear ? DATE_FORMATTER : DATE_WITH_YEAR_FORMATTER).format(date)} ${time}`;