Skip to content

Instantly share code, notes, and snippets.

@vasanthv
Last active August 13, 2017 09:59
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 vasanthv/cf8c91c484e3ef2511946c1300094d8a to your computer and use it in GitHub Desktop.
Save vasanthv/cf8c91c484e3ef2511946c1300094d8a to your computer and use it in GitHub Desktop.
function timeAgo(time){
var units = [
{ name: "second", limit: 60, in_seconds: 1 },
{ name: "minute", limit: 3600, in_seconds: 60 },
{ name: "hour", limit: 86400, in_seconds: 3600 },
{ name: "day", limit: 604800, in_seconds: 86400 },
{ name: "week", limit: 2629743, in_seconds: 604800 },
{ name: "month", limit: 31556926, in_seconds: 2629743 },
{ name: "year", limit: null, in_seconds: 31556926 }
];
var diff = (new Date() - new Date(time)) / 1000;
if (diff < 5) return "now";
var i = 0, unit;
while (unit = units[i++]) {
if (diff < unit.limit || !unit.limit){
var diff = Math.floor(diff / unit.in_seconds);
return diff + " " + unit.name + (diff>1 ? "s" : "");
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment