Skip to content

Instantly share code, notes, and snippets.

@ChukwuEmekaAjah
Created August 28, 2022 20:01
Show Gist options
  • Save ChukwuEmekaAjah/2d8e850fb64ca0f3673f6b3a5c7c4194 to your computer and use it in GitHub Desktop.
Save ChukwuEmekaAjah/2d8e850fb64ca0f3673f6b3a5c7c4194 to your computer and use it in GitHub Desktop.
Return how long ago an event occurred with respect to current time.
const pluralize = function (value){
return Math.floor(value) > 1 ? 's' : '';
}
function ago(date){
const now = Math.floor(Date.now()/1000)
const time = new Date(date)
if(isNaN(time.getTime())){
throw new Error(`Passed in date ${date} is not a valid date`)
}
const parsed_time = Math.floor(time.getTime()/1000)
const ranges = {
second: 60, // max of 60 seconds before we get to minute
minute: 3600, // max of 3600 seconds (60 mins) before we get to hour
hour: 86400, // max of 86400 seconds (24 hours) before we get to a day
day: 2592000, // max of 2592000 seconds (30 days) before we get to a day
month: 31536000, // max of 31536000 seconds (12 months) before we get to a day
}
const difference = now - parsed_time
if(difference < 0){
throw new Error(`Passed in date ${date} is in the future`)
}
if (difference < 60){
return `${difference} second${pluralize(difference)} ago`;
} else if (difference < 3600){
return `${Math.floor(difference/ranges.second)} minute${pluralize(difference/ranges.second)} ago`;
} else if(difference < ranges.hour){
return `${Math.floor(difference/ranges.minute)} hour${pluralize(difference/ranges.minute)} ago`;
} else if(difference < ranges.day){
return `${Math.floor(difference/ranges.hour)} day${pluralize(difference/ranges.hour)} ago`;
} else if(difference < ranges.month){
return `${Math.floor(difference/ranges.day)} month${pluralize(difference/ranges.day)} ago`;
} else{
return `${Math.floor(difference/ranges.month)} year${pluralize(difference/ranges.month)} ago`;
}
}
module.exports = ago
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment