Last active
December 10, 2024 14:39
-
-
Save jschatz1/5ec752e8c37072be8dd20ee1269dd314 to your computer and use it in GitHub Desktop.
TimeHelper.js
This file contains hidden or 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
const TimeHelper = (() => { | |
const units = [ | |
{ name: 'year', millis: 31536000000 }, | |
{ name: 'month', millis: 2592000000 }, | |
{ name: 'week', millis: 604800000 }, | |
{ name: 'day', millis: 86400000 }, | |
{ name: 'hour', millis: 3600000 }, | |
{ name: 'minute', millis: 60000 }, | |
{ name: 'second', millis: 1000 }, | |
]; | |
const formatRelativeTime = (date, baseDate = new Date()) => { | |
const elapsed = date - baseDate; | |
const absElapsed = Math.abs(elapsed); | |
for (const unit of units) { | |
const delta = Math.round(absElapsed / unit.millis); | |
if (delta >= 1) { | |
const formatter = new Intl.RelativeTimeFormat('en', { numeric: 'auto' }); | |
return formatter.format(Math.sign(elapsed) * delta, unit.name); | |
} | |
} | |
return 'just now'; | |
}; | |
return { | |
fromNow: (date) => formatRelativeTime(new Date(date)), | |
}; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment