const RTF = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
const STEPS: Array<[Intl.RelativeTimeFormatUnit, number]> = [
['year', 31_536_000_000],
['month', 2_592_000_000],
['week', 604_800_000],
['day', 86_400_000],
['hour', 3_600_000],
['minute', 60_000],
['second', 1_000],
];
export function timeAgo(when: Date | number | string): string {
const target = typeof when === 'object' ? when.getTime() : new Date(when).getTime();
const diff = target - Date.now();
const abs = Math.abs(diff);
for (const [unit, ms] of STEPS) {
if (abs >= ms || unit === 'second') {
return RTF.format(Math.round(diff / ms), unit);
}
}
return 'now';
}
timeAgo(Date.now() - 60_000); // 'yesterday' / '1 minute ago' depending on numeric mode
timeAgo(Date.now() + 86_400_000); // 'tomorrow'
Create a free account and build your private vault. Share publicly whenever you want.