Add timeAgo util function
This commit is contained in:
parent
aa20d0d4ac
commit
da18658a5f
1 changed files with 26 additions and 0 deletions
26
utils/timeAgo.tsx
Normal file
26
utils/timeAgo.tsx
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
|
||||
const DIVISIONS = [
|
||||
{ amount: 60, name: 'seconds' },
|
||||
{ amount: 60, name: 'minutes' },
|
||||
{ amount: 24, name: 'hours' },
|
||||
{ amount: 7, name: 'days' },
|
||||
{ amount: 4.34524, name: 'weeks' },
|
||||
{ amount: 12, name: 'months' },
|
||||
{ amount: Number.POSITIVE_INFINITY, name: 'years' }
|
||||
]
|
||||
|
||||
export function formatTimeAgo(date: Date, locale: string = 'en-us') {
|
||||
const formatter = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' })
|
||||
|
||||
let duration = (date.getTime() - new Date().getTime()) / 1000
|
||||
|
||||
for (let i = 0; i <= DIVISIONS.length; i++) {
|
||||
const division = DIVISIONS[i]
|
||||
|
||||
if (Math.abs(duration) < division.amount) {
|
||||
return formatter.format(Math.round(duration), division.name)
|
||||
}
|
||||
|
||||
duration /= division.amount
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue