Files
personal-website/src/lib/relative-time.ts
Stan Runge d0c7b6548b
Some checks failed
Test and deploy staging / staging (push) Has been cancelled
beeeeg update
2026-09-23 04:16:50 +00:00

27 lines
813 B
TypeScript

export function relativeTime(date: Date | string, now: number) {
const elapsed = Math.max(0, Math.floor((now - new Date(date).getTime()) / 1000));
if (elapsed < 5) return 'just now';
const units: [number, string][] = [
[31_536_000, 'year'],
[2_592_000, 'month'],
[604_800, 'week'],
[86_400, 'day'],
[3_600, 'hour'],
[60, 'minute'],
[1, 'second']
];
for (const [seconds, unit] of units) {
if (elapsed >= seconds) {
const count = Math.floor(elapsed / seconds);
return `${count === 1 ? (unit === 'hour' ? 'an' : 'a') : count} ${unit}${count === 1 ? '' : 's'} ago`;
}
}
return 'just now';
}
const dateFormatter = new Intl.DateTimeFormat('en', { dateStyle: 'long', timeZone: 'UTC' });
export function calendarDate(date: Date | string) {
return dateFormatter.format(new Date(date));
}