Menu

How To Get Time Interval (Time Ago) In Javascript.

Hello Guys,
This tutorial is based on javascript. Today we will learn how we can get a time ago with javascript. Sometimes we want to show how old is our post or any article instead of DateTime.
There are lots of plugins are available for this. We will do this without any plugins.
Let's start

Get Time Ago 

function timeAgo(date) {
  let seconds = Math.floor((Date.now() - date) / 1000);
  let unit = "second";
  let direction = "ago";
  if (seconds < 0) {
    seconds = -seconds;
    direction = "from now";
  }
  let value = seconds;
  if (seconds >= 31536000) {
    value = Math.floor(seconds / 31536000);
    unit = "year";
  } else if (seconds >= 86400) {
    value = Math.floor(seconds / 86400);
    unit = "day";
  } else if (seconds >= 3600) {
    value = Math.floor(seconds / 3600);
    unit = "hour";
  } else if (seconds >= 60) {
    value = Math.floor(seconds / 60);
    unit = "minute";
  }
  if (value != 1)
    unit = unit + "s";
  return value + " " + unit + " " + direction;
}

console.log(timeAgo(Date.now())); // 0 seconds ago
console.log(timeAgo(Date.now() + 1000)); // 1 second from now
console.log(timeAgo(Date.now() - 1000)); // 1 second ago
console.log(timeAgo(Date.now() + 60000)); // 1 minute from now
console.log(timeAgo(Date.now() - 120000)); // 2 minutes ago
console.log(timeAgo(Date.now() + 120000)); // 2 minutes from now
console.log(timeAgo(Date.now() + 3600000)); // 1 hour from now
console.log(timeAgo(Date.now() + 360000000000)); // 11 years from now

This function will help you to get future and past time diff in a human-readable format.
You can also modify this according to your requirement.
Hope this tutorial will save your time.
Please share this post with others.

Thanks

 

714
Search

Ads