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

timestampFormat.ts

160 lines5.8 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;
74​
75/**
76 * Relative elapsed duration since an ISO instant, without an "ago" suffix.
77 * Useful for labels like "Connected for 3m".
78 */
79export function formatElapsedDurationLabel(isoDate: string, nowMs: number = Date.now()): string {
80 const diffMs = nowMs - new Date(isoDate).getTime();
81 if (diffMs <= 0) return "just now";
82​
83 const seconds = Math.floor(diffMs / 1000);
84 if (seconds < 5) return "just now";
85 if (seconds < 60) return `${seconds}s`;
86​
87 const minutes = Math.floor(seconds / 60);
88 if (minutes < 60) return `${minutes}m`;
89​
90 const hours = Math.floor(minutes / 60);
91 if (hours < 24) return `${hours}h`;
92​
93 const days = Math.floor(hours / 24);
94 return `${days}d`;
96​
97/**
98 * Relative time until an ISO instant (e.g. expiry). Mirrors {@link formatRelativeTime} but for future times.
99 */
100export function formatRelativeTimeUntil(isoDate: string): { value: string; suffix: string | null } {
101 const diffMs = new Date(isoDate).getTime() - Date.now();
102 if (diffMs <= 0) return { value: "Expired", suffix: null };
103 const seconds = Math.floor(diffMs / 1000);
104 if (seconds < 5) return { value: "Soon", suffix: null };
105 if (seconds < 60) return { value: `${seconds}s`, suffix: "left" };
106 const minutes = Math.floor(seconds / 60);
107 if (minutes < 60) return { value: `${minutes}m`, suffix: "left" };
108 const hours = Math.floor(minutes / 60);
109 if (hours < 24) return { value: `${hours}h`, suffix: "left" };
110 const days = Math.floor(hours / 24);
111 return { value: `${days}d`, suffix: "left" };
113​
114export function formatRelativeTimeUntilLabel(isoDate: string): string {
115 const relative = formatRelativeTimeUntil(isoDate);
116 return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value;
118​
119/**
120 * Countdown for a future instant (e.g. link expiry): "Expires in 4m 12s", with second precision under one hour.
121 * Pass `nowMs` when a parent tick drives re-renders so the diff matches that snapshot.
122 */
123export function formatExpiresInLabel(isoDate: string, nowMs: number = Date.now()): string {
124 const diffMs = new Date(isoDate).getTime() - nowMs;
125 if (diffMs <= 0) return "Expired";
126​
127 const totalSeconds = Math.floor(diffMs / 1000);
128 if (totalSeconds < 5) return "Expires in a moment";
129 if (totalSeconds < 60) return `Expires in ${totalSeconds}s`;
130​
131 if (totalSeconds < 3600) {
132 const minutes = Math.floor(totalSeconds / 60);
133 const seconds = totalSeconds % 60;
134 return seconds === 0 ? `Expires in ${minutes}m` : `Expires in ${minutes}m ${seconds}s`;
135 }
136​
137 if (totalSeconds < 86_400) {
138 const hours = Math.floor(totalSeconds / 3600);
139 const rem = totalSeconds % 3600;
140 const minutes = Math.floor(rem / 60);
141 const seconds = rem % 60;
142 const parts = [`${hours}h`];
143 if (minutes > 0) parts.push(`${minutes}m`);
144 if (seconds > 0) parts.push(`${seconds}s`);
145 return `Expires in ${parts.join(" ")}`;
146 }
147​
148 const days = Math.floor(totalSeconds / 86_400);
149 const remAfterDays = totalSeconds % 86_400;
150 if (remAfterDays === 0) return `Expires in ${days}d`;
151 const hours = Math.floor(remAfterDays / 3600);
152 const rem = remAfterDays % 3600;
153 const minutes = Math.floor(rem / 60);
154 const seconds = rem % 60;
155 const tail: string[] = [];
156 if (hours > 0) tail.push(`${hours}h`);
157 if (minutes > 0) tail.push(`${minutes}m`);
158 if (seconds > 0) tail.push(`${seconds}s`);
159 return tail.length > 0 ? `Expires in ${days}d ${tail.join(" ")}` : `Expires in ${days}d`;