Skip to content

Instantly share code, notes, and snippets.

@vespoli
Last active August 29, 2015 13:56
Show Gist options
  • Save vespoli/8829691 to your computer and use it in GitHub Desktop.
Save vespoli/8829691 to your computer and use it in GitHub Desktop.
Time ago - Returns a string with a string containing an approximation time since the date. ie: "5 minutes", "2 days", "10 years"
Date.prototype.timeAgo = function(){
var seconds = Math.floor((new Date() - this) / 1000);
var interval = Math.floor(seconds / 31536000);
if (interval > 1) {return interval + " years";}
if (interval === 1) {return interval + " year";}
interval = Math.floor(seconds / 2592000);
if (interval > 1) { return interval + " months";}
if (interval === 1) {return interval + " month";}
interval = Math.floor(seconds / 86400);
if (interval > 1) {return interval + " days";}
if (interval === 1) {return interval + " day";}
interval = Math.floor(seconds / 3600);
if (interval > 1) {return interval + " hours";}
if (interval === 1) {return interval + " hour";}
interval = Math.floor(seconds / 60);
if (interval > 1) {return interval + " minutes";}
if (interval === 1) {return interval + " minute";}
return Math.floor(seconds) + " seconds";
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment