Created
October 29, 2022 17:12
-
-
Save nounderline/a925d9fa1242ed4d7ca8a01b9835a601 to your computer and use it in GitHub Desktop.
Relative time ago with native Intl.RelativeTimeFormat in JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* From: 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' } | |
] | |
function 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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment