repod/src/utils/time.js
Michel Roux 43dfa54d64
All checks were successful
repod / nextcloud (push) Successful in 54s
repod / nodejs (push) Successful in 1m21s
Search completed
2023-07-28 01:52:48 +02:00

28 lines
738 B
JavaScript

// https://blog.webdevsimplified.com/2020-07/relative-time-format/
const formatter = new Intl.RelativeTimeFormat(undefined, {
numeric: 'auto',
})
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 const formatTimeAgo = (date) => {
let duration = (date - new Date()) / 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
}
}