A function to display time since a certain date.

7 years ago
JavaScript
Date
DateTime
CodePen

Sometimes we want to simply display how much time has passed on a certain date. Hence, I created a very simple function to display this. Here it is;

function timeAgo(d){
  const diff = (new Date() - d)/1000;
  if(diff<60){
    const v = Math.round(diff)
    return v + ' second' + (v===1?'':'s') + ' ago';   
  }
  else if(diff<60*60){
    const v = Math.round(diff/60)
    return v + ' minute' + (v===1?'':'s') + ' ago';   
  }
  else if(diff<60*60*24){
    const v = Math.round(diff/(60*60))
    return v + ' hour' + (v===1?'':'s') + ' ago';   
  }
  else if(diff<60*60*24*30.436875){
    const v = Math.round(diff/(60*60*24))
    return v + ' day' + (v===1?'':'s') + ' ago';
  }
  else if(diff<60*60*24*30.436875*12){
    const v = Math.round(diff/(60*60*24*30.436875))
    return v + ' month' + (v===1?'':'s') + ' ago';
  }
  const v = Math.round(diff/(60*60*24*30.436875*12)) 
  return v + ' year' + (v===1?'':'s') + ' ago';
}

Here is the code in the codepen for ease of experimentation or as a sample on how it can be used, https://codepen.io/mjunaidi/pen/RLOQRO.

A little bit details about the number used to measure how many time has passed;

 const diff = (new Date() - d)/1000;

As the current date object and its difference is returning an integer in milliseconds, we convert the value to seconds first by divinding it by 1000. Hence we get variable diff in seconds.

If the difference value is less than 60 seconds (1 minute), it means the value is just a few seconds ago.

If the value is bigger than 60 but less than an hour (60 minutes 脳 60 &seconds; or 1 minute), so the value in minutes ago.

Then, if the value is less than a day (24 hours 脳 60 minutes 脳 60 seconds), so we get a value in hours ago.

Then, if the value is less than a month (30.436875 days 脳 24 hours 脳 60 minutes 脳 60 seconds), we would get a value in days ago.

The value 30.436875 is a value of an average day in any month per 400 years. You can refer this from other sources, for example here, https://en.wikipedia.org/wiki/Month. Or try to look up for The mean month length of the Gregorian calendar.

Then, if the value is less than a year (60602430.43687512), it means the value is in months ago.

And finally, we assume the value is in years ago.

Thanks for reading!