Skip to content

Instantly share code, notes, and snippets.

@yifeiyin
Created January 19, 2021 04:59
Show Gist options
  • Save yifeiyin/10713277e8d49ea83184c447f5a0b33b to your computer and use it in GitHub Desktop.
Save yifeiyin/10713277e8d49ea83184c447f5a0b33b to your computer and use it in GitHub Desktop.
Format relative date
/*
* [Relative Date Internationalization In JavaScript | Web Dev Simplified Blog](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