JavaScript: How to Convert Date Time to Time Ago

Updated: February 19, 2023 By: Frienzied Flame Post a comment

Time ago is the concept of expressing a time relative to the current time. For example, if it is currently 3 pm and we want to talk about the moment at 1 pm, then we can say 2 hours ago. Time ago is widely used in modern applications like social media, news, etc., to convey how long ago an event happened in a friendly manner.

So, how do you convert date time to time ago in Javascript? Let’s find out in the example below:

// Define a function that takes a date as an argument
// and returns a string that represents how long ago the date was
export const timeAgo = (date) => {
  const seconds = Math.floor((new Date() - date) / 1000);

  let interval = Math.floor(seconds / 31536000);
  if (interval > 1) {
    return interval + ' years ago';
  }

  interval = Math.floor(seconds / 2592000);
  if (interval > 1) {
    return interval + ' months ago';
  }

  interval = Math.floor(seconds / 86400);
  if (interval > 1) {
    return interval + ' days ago';
  }

  interval = Math.floor(seconds / 3600);
  if (interval > 1) {
    return interval + ' hours ago';
  }

  interval = Math.floor(seconds / 60);
  if (interval > 1) {
    return interval + ' minutes ago';
  }

  if(seconds < 10) return 'just now';

  return Math.floor(seconds) + ' seconds ago';
};

// at the time of writing this code, the date is 2022-12-28 16:14:00
// you will see different results if you run this code at different time
console.log(timeAgo(new Date('2019-01-29 00:00:00')))
console.log(timeAgo(new Date('2022-10-24 19:00:00')))
console.log(timeAgo(Date.now() - 60 * 5 * 1000))

My output:

3 years ago
2 months ago
5 minutes ago

You can reuse the timeAgo function we’ve created above in your future projects so that you don’t have to rewrite all the code. It works nicely, and the job is done with only vanilla Javascript. No third-party libraries are necessary.