Skip to content

Instantly share code, notes, and snippets.

@johnjullies
Created August 9, 2015 13:47
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 johnjullies/810010db8acbb6175aa6 to your computer and use it in GitHub Desktop.
Save johnjullies/810010db8acbb6175aa6 to your computer and use it in GitHub Desktop.
The question is how to format a JavaScript Date as a string stating the time elapsed similar to the way you see times displayed on Stack Overflow. e.g. 1 minute ago 1 hour ago 1 day ago 1 month ago 1 year ago
function timeSince(date) {
var seconds = Math.floor((new Date() - date) / 1000);
var interval = Math.floor(seconds / 31536000);
if (interval > 1) {
return interval + " years";
}
interval = Math.floor(seconds / 2592000);
if (interval > 1) {
return interval + " months";
}
interval = Math.floor(seconds / 86400);
if (interval > 1) {
return interval + " days";
}
interval = Math.floor(seconds / 3600);
if (interval > 1) {
return interval + " hours";
}
interval = Math.floor(seconds / 60);
if (interval > 1) {
return interval + " minutes";
}
return Math.floor(seconds) + " seconds";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment