16 lines
670 B
TypeScript
16 lines
670 B
TypeScript
|
|
function plural(num: number, unit: string): string {
|
||
|
|
const whole = Math.floor(num)
|
||
|
|
return whole + ' ' + unit + (whole === 1 ? '' : 's')
|
||
|
|
}
|
||
|
|
|
||
|
|
export function ago(date: Date): string {
|
||
|
|
const now = new Date()
|
||
|
|
const diff = now.getTime() - date.getTime()
|
||
|
|
if (diff < 1000) return 'just now'
|
||
|
|
if (diff < 60 * 1000) return plural(diff / 1000, 'second') + ' ago'
|
||
|
|
if (diff < 60 * 60 * 1000) return plural(diff / (60 * 1000), 'minute') + ' ago'
|
||
|
|
if (diff < 24 * 60 * 60 * 1000) return plural(diff / (60 * 60 * 1000), 'hour') + ' ago'
|
||
|
|
if (diff < 7 * 24 * 60 * 60 * 1000) return plural(diff / (24 * 60 * 60 * 1000), 'day') + ' ago'
|
||
|
|
return date.toLocaleDateString()
|
||
|
|
}
|