11 August 2020   |   by Pratyush Aswal   |   Coding, Blogs

Determining time since a given timestamp

"x" hours ago functionality on websites

Whenever we see a blog post or a comment we always find the time since it is posted(2hours ago, 5minutes ago, etc). Today we will build a JavaScript function for this functionality. We need one thing for this, which is the timestamp of the event when that particular event happened.

Function description:

Let us call our function as "timeSince(timestamp)". Here, "timestamp" is the timestamp of the event. Now we will go step by step and return the time since the event happened.

  1. We will calculate the difference between the current timestamp and the given timestamp in seconds. Now keep in mind that direct subtraction between timestamps will give you milliseconds so don't forget to divide the result by 1000.
  2. Now we will make our time interval with the name "interval". We will set our first interval to one year so we will calculate the number of years in the result of the first step. Here, we will divide the number of seconds calculated in the first step and divide it with the number of seconds in one year which will give us the time interval in years.
  3. Now check if the interval is greater than 0. If so, return the interval which will give us time since "interval years ago".
  4. If the interval is less than zero then the difference between the timestamps is less than a year (maybe in months, days, etc). Now divide the number of seconds calculated in step 1 with the number of seconds in a month (take 2592000) and set it as the new interval.
  5. As you checked for year similarly, check the interval for a month and return the number of months if the interval is greater than 0 else continue with step 6.
  6. Set the interval equal to the number of days(seconds/86400) in the number of seconds calculated in step one and check interval again.
  7. If the interval is still less than zero. set the interval to the number of hours present in the difference calculated in step one (seconds/3600). Check the interval again and if it is still less than zero proceed to step eight.
  8. Set the interval to (seconds / 60) to calculate the number of minutes since the event happened. If the interval is greater than zero, return the number of minutes. Else, return "a few seconds ago".

  9. Whole function: