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

time.ts

44 lines1.6 KB

1// Host timestamps may carry UTC offsets or mixed fractions, so text order is not time order.
2export function compareTimestamps(left: string, right: string): number {
3 return (Date.parse(left) || 0) - (Date.parse(right) || 0);
4}
5​
6export function byTimestamp(newestFirst: boolean) {
7 return (left: { readonly date: string }, right: { readonly date: string }) =>
8 newestFirst
9 ? compareTimestamps(right.date, left.date)
10 : compareTimestamps(left.date, right.date);
12​
13export function relativeTime(input: string, nowMs: number = Date.now()): string {
14 const timestamp = Date.parse(input);
15 if (Number.isNaN(timestamp)) {
16 return "<1m";
17 }
18​
19 const deltaSeconds = Math.max(0, Math.floor((nowMs - timestamp) / 1000));
20 if (deltaSeconds < 60) return "<1m";
21​
22 const deltaMinutes = Math.floor(deltaSeconds / 60);
23 if (deltaMinutes < 60) return `${deltaMinutes}m`;
24​
25 const deltaHours = Math.floor(deltaMinutes / 60);
26 if (deltaHours < 24) return `${deltaHours}h`;
27​
28 const deltaDays = Math.floor(deltaHours / 24);
29 return `${deltaDays}d`;
31​
32/** Milliseconds until the relative-time label next changes. */
33export function msUntilRelativeTimeChange(
34 input: string,
35 nowMs: number = Date.now(),
36): number | null {
37 const timestamp = Date.parse(input);
38 if (Number.isNaN(timestamp)) return null;
39 const elapsedMs = Math.max(0, nowMs - timestamp);
40 const unitMs = elapsedMs < 3_600_000 ? 60_000 : elapsedMs < 86_400_000 ? 3_600_000 : 86_400_000;
41 const nextChangeMs = timestamp + (Math.floor(elapsedMs / unitMs) + 1) * unitMs;
42 // Far-future timestamps must not overflow setTimeout's signed 32-bit delay.
43 return Math.min(nextChangeMs - nowMs, 86_400_000);