Skip to content

Instantly share code, notes, and snippets.

@mattdodge
Created March 2, 2015 19:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattdodge/90704ecbbfecc78be50f to your computer and use it in GitHub Desktop.
Save mattdodge/90704ecbbfecc78be50f to your computer and use it in GitHub Desktop.
Human Readable Time Difference
function timeAgo(num_seconds) {
function numberEnding (number) {
return (number > 1) ? 's ago' : ' ago';
}
if (num_seconds <= 0) {
return 'just now!';
}
var years = Math.floor(num_seconds / 31536000);
if (years) {
return years + ' yr' + numberEnding(years);
}
var days = Math.floor((num_seconds %= 31536000) / 86400);
if (days) {
return days + ' day' + numberEnding(days);
}
var hours = Math.floor((num_seconds %= 86400) / 3600);
if (hours) {
return hours + ' hr' + numberEnding(hours);
}
var minutes = Math.floor((num_seconds %= 3600) / 60);
if (minutes) {
return minutes + ' min' + numberEnding(minutes);
}
if (num_seconds < 60) {
return num_seconds + ' sec' + numberEnding(num_seconds);
}
return 'just now!';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment