CODE CODIFY.CLUB

Time ago function in Javascript

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.

  • 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";
}

var date1 = new Date("05-15-2018 10:00:00"); // m/d/y
var tm = date1.getTime();

console.log(tm);
console.log(timeSince(tm));

V!ral

Developer, Technology aficionado, Beer Lover and founder of codify.club Network. Who shares a keen interest about website development, health issues, cancer awareness and other fun stuff.

Add comment

Follow us

Don't be shy, get in touch. We love meeting interesting people and making new friends.

Most popular

Most discussed