Skip to content

Instantly share code, notes, and snippets.

@3rdp
Forked from patrickmooney/time ago in vanilla js
Last active August 26, 2020 16:50
Show Gist options
  • Save 3rdp/c1e4eec0ab4226b4893f213cec430d66 to your computer and use it in GitHub Desktop.
Save 3rdp/c1e4eec0ab4226b4893f213cec430d66 to your computer and use it in GitHub Desktop.
function timeSince(timeStamp) {
var now = new Date(),
secondsPast = (now.getTime() - timeStamp.getTime()) / 1000;
if(secondsPast < 60){
return [-parseInt(secondsPast), 'seconds']
}
if(secondsPast < 3600){
return [-parseInt(secondsPast/60), 'minutes']
}
if(secondsPast <= 86400){
return [-parseInt(secondsPast/3600), 'hours']
}
if(secondsPast <= 86400 * 7) {
return [-parseInt(secondsPast/86400), 'day']
}
return [-parseInt(secondsPast/(86400 * 7)), 'week']
}
function formatRelativeTime(date, locale) {
return new Intl.RelativeTimeFormat(locale).format(...timeSince(date))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment