This commit is contained in:
26
src/lib/relative-time.ts
Normal file
26
src/lib/relative-time.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
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));
|
||||
}
|
||||
Reference in New Issue
Block a user