Created
December 15, 2025 10:24
-
-
Save jakubfiala/25b5e59dbebeae2e8d9459c605bc9e72 to your computer and use it in GitHub Desktop.
A simple implementation of human-readable relative time. Don't use dodgy NPM packages for this. It's really not that complicated to build in 2025.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Don't use dodgy NPM packages for this. It's really not that complicated to build in 2025 | |
| type GranularityInfo = { | |
| unit: Intl.RelativeTimeFormatUnit; | |
| intervalMs: number; | |
| }; | |
| const getGranularityForTimestampDiff = (diff: number): GranularityInfo => { | |
| if (diff > 86_400_000) { | |
| return { unit: "day", intervalMs: 86_400_000 }; | |
| } else if (diff > 3_600_000) { | |
| return { unit: "hour", intervalMs: 3_600_000 }; | |
| } else if (diff > 60_000) { | |
| return { unit: "minute", intervalMs: 60_000 }; | |
| } | |
| return { unit: "second", intervalMs: 1_000 }; | |
| }; | |
| const formatter = new Intl.RelativeTimeFormat([ | |
| navigator.language.split("-").at(0) ?? "en", | |
| ]); | |
| const getHumanReadableRelativeTime = (t1: number, t2: number): string => { | |
| const diff = t2 - t1; | |
| const { unit, intervalMs } = getGranularityForTimestampDiff(diff); | |
| return formatter.format(-1 * Math.floor(diff / intervalMs), unit); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment