(
timestampMs: number,
options: RelativeTimeFormatOptions = {}
)
| 12 | } |
| 13 | |
| 14 | export function formatRelativeTime( |
| 15 | timestampMs: number, |
| 16 | options: RelativeTimeFormatOptions = {} |
| 17 | ): string { |
| 18 | const { nowThresholdMs = DEFAULT_NOW_THRESHOLD_MS } = options; |
| 19 | const diffMs = Date.now() - timestampMs; |
| 20 | const absDiff = Math.abs(diffMs); |
| 21 | const sign = diffMs >= 0 ? -1 : 1; |
| 22 | |
| 23 | const rtf = new Intl.RelativeTimeFormat(getActiveLocale(), { |
| 24 | numeric: "auto", |
| 25 | }); |
| 26 | |
| 27 | if (absDiff < nowThresholdMs) { |
| 28 | return rtf.format(0, "second"); |
| 29 | } |
| 30 | if (absDiff < 60_000) { |
| 31 | return rtf.format(sign * Math.round(absDiff / 1000), "second"); |
| 32 | } |
| 33 | if (absDiff < 3_600_000) { |
| 34 | return rtf.format(sign * Math.round(absDiff / 60_000), "minute"); |
| 35 | } |
| 36 | if (absDiff < 86_400_000) { |
| 37 | return rtf.format(sign * Math.round(absDiff / 3_600_000), "hour"); |
| 38 | } |
| 39 | return rtf.format(sign * Math.round(absDiff / 86_400_000), "day"); |
| 40 | } |
| 41 | |
| 42 | export function formatAbsoluteDateTime(timestampMs: number): string { |
| 43 | return new Intl.DateTimeFormat(getActiveLocale(), { |
no test coverage detected