Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

timestampFormat.ts

73 lines2.5 KB

1import { type TimestampFormat } from "@t3tools/contracts/settings";
2​
3export function getTimestampFormatOptions(
4 timestampFormat: TimestampFormat,
5 includeSeconds: boolean,
6): Intl.DateTimeFormatOptions {
7 const baseOptions: Intl.DateTimeFormatOptions = {
8 hour: "numeric",
9 minute: "2-digit",
10 ...(includeSeconds ? { second: "2-digit" } : {}),
11 };
12​
13 if (timestampFormat === "locale") {
14 return baseOptions;
15 }
16​
17 return {
18 ...baseOptions,
19 hour12: timestampFormat === "12-hour",
20 };
22​
23const timestampFormatterCache = new Map<string, Intl.DateTimeFormat>();
24​
25function getTimestampFormatter(
26 timestampFormat: TimestampFormat,
27 includeSeconds: boolean,
28): Intl.DateTimeFormat {
29 const cacheKey = `${timestampFormat}:${includeSeconds ? "seconds" : "minutes"}`;
30 const cachedFormatter = timestampFormatterCache.get(cacheKey);
31 if (cachedFormatter) {
32 return cachedFormatter;
33 }
34​
35 const formatter = new Intl.DateTimeFormat(
36 undefined,
37 getTimestampFormatOptions(timestampFormat, includeSeconds),
38 );
39 timestampFormatterCache.set(cacheKey, formatter);
40 return formatter;
42​
43export function formatTimestamp(isoDate: string, timestampFormat: TimestampFormat): string {
44 return getTimestampFormatter(timestampFormat, true).format(new Date(isoDate));
46​
47export function formatShortTimestamp(isoDate: string, timestampFormat: TimestampFormat): string {
48 return getTimestampFormatter(timestampFormat, false).format(new Date(isoDate));
50​
51/**
52 * Format a relative time string from an ISO date.
53 * Returns `{ value: "20s", suffix: "ago" }` or `{ value: "just now", suffix: null }`
54 * so callers can style the numeric portion independently.
55 */
56export function formatRelativeTime(isoDate: string): { value: string; suffix: string | null } {
57 const diffMs = Date.now() - new Date(isoDate).getTime();
58 if (diffMs < 0) return { value: "just now", suffix: null };
59 const seconds = Math.floor(diffMs / 1000);
60 if (seconds < 5) return { value: "just now", suffix: null };
61 if (seconds < 60) return { value: `${seconds}s`, suffix: "ago" };
62 const minutes = Math.floor(seconds / 60);
63 if (minutes < 60) return { value: `${minutes}m`, suffix: "ago" };
64 const hours = Math.floor(minutes / 60);
65 if (hours < 24) return { value: `${hours}h`, suffix: "ago" };
66 const days = Math.floor(hours / 24);
67 return { value: `${days}d`, suffix: "ago" };
69​
70export function formatRelativeTimeLabel(isoDate: string) {
71 const relative = formatRelativeTime(isoDate);
72 return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value;