tooot/src/utils/relativeTime.ts

30 lines
718 B
TypeScript
Raw Normal View History

2020-12-13 14:04:25 +01:00
import { store } from '@root/store'
2020-11-30 00:24:53 +01:00
2020-10-31 21:04:46 +01:00
const relativeTime = (date: string) => {
2020-11-30 00:24:53 +01:00
const units = {
year: 24 * 60 * 60 * 1000 * 365,
month: (24 * 60 * 60 * 1000 * 365) / 12,
day: 24 * 60 * 60 * 1000,
hour: 60 * 60 * 1000,
minute: 60 * 1000,
second: 1000
}
2020-11-30 00:24:53 +01:00
const rtf = new Intl.RelativeTimeFormat(store.getState().settings.language, {
numeric: 'auto'
})
2020-11-30 00:24:53 +01:00
const elapsed = +new Date(date) - +new Date()
// "Math.abs" accounts for both "past" & "future" scenarios
2020-11-30 00:24:53 +01:00
for (const u in units) {
// @ts-ignore
if (Math.abs(elapsed) > units[u] || u == 'second') {
// @ts-ignore
return rtf.format(Math.round(elapsed / units[u]), u)
2020-11-30 00:24:53 +01:00
}
}
}
2020-10-23 09:22:17 +02:00
2020-10-31 21:04:46 +01:00
export default relativeTime