Skip to content

Instantly share code, notes, and snippets.

@jakubfiala
Created December 15, 2025 10:24
Show Gist options
  • Select an option

  • Save jakubfiala/25b5e59dbebeae2e8d9459c605bc9e72 to your computer and use it in GitHub Desktop.

Select an option

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.
// 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