Get the relative timestamp difference between dates in JavaScript


Have you ever seen notifications on any website showing the time stamp? It shows something like “12 minutes ago”, “2 days ago”, “10 hours ago”, etc. It is related to the timestamp difference between two dates or times.

Also, some apps show that this device's last login was 22 hours ago. So, there are many uses to get the timestamp difference between two dates.

In this tutorial, we will learn different approaches to get the relative timestamp difference between two dates.

Use the getTime() method with the date and create a custom algorithm

In JavaScript, we can create a date object using the new Date() constructor. Also, we can pass a particular date as a parameter of the Date() constructor to initialize the date object with that date value.

The getTime() method returns the total seconds from 1st January 1970 to till date. So, we can find the total milliseconds for both dates and minus them to get the difference of milliseconds. Using that millisecond, we can find the timestamp difference in seconds, minutes, years, etc.

Syntax

Users can follow the syntax below to get the relative timestamp difference between the two dates.

let second_diff = (current_date.getTime() - previous_date.getTime())/1000; 

In the above syntax, current_date, and pervious_date are two different dates. We used the getTime() method to get the difference of milliseconds between the two dates.

Note − By comparing the value of the second_diff variable with milliseconds, you can get a relative timestamp difference.

Steps

Users can follow the below steps to find relative timestamps between two dates in different units such as days, months, years, etc.

Step 1 − Create two different dates.

Step 2 − Use the getTime() method to get the total milliseconds for both dates and take the difference between them. Also, divide the difference of milliseconds by 1000 to convert it into seconds, and store it in the second_diff variable.

Step 3 − Now, use the if-else conditional statement to find the relative timestamp difference.

Step 4 − If second_diff’s value is less than 60, the difference is in seconds. The value of second_diff is between 60 and 3600, and the difference is in hours. Users can also calculate the days, months, and years like this.

Example

In the example below, we have created two different date objects using the Date constructor and used the above steps to find the relative timestamp between two dates.

In the output, users can observe that the below code represents the timestamp difference in the months.

<html>
<body>
   <h3>Getting the relative timestamp difference between two dates using the <i> custom algorithm </i></h3>
   <p id="output"></p>
   <script>
      let output = document.getElementById("output");
      
      // creating the current date
      let current_date = new Date();
      
      // previous date
      let previous_date = new Date("jan 14, 2022 12:21:45");
      
      // finding the difference in total seconds between two dates
      let second_diff = (current_date.getTime() - previous_date.getTime()) / 1000;
      output.innerHTML += "The first date is " + current_date + "</br>";
      output.innerHTML += "The second date is " + previous_date + "</br>";
      
      // showing the relative timestamp.
      if (second_diff < 60) {
         output.innerHTML += "difference is of " + second_diff + " seconds.";
      } else if (second_diff < 3600) {
         output.innerHTML += "difference is of " + second_diff / 60 + " minutes.";
      } else if (second_diff < 86400) {
         output.innerHTML += "difference is of " + second_diff / 3600 + " hours.";
      } else if (second_diff < 2620800) {
         output.innerHTML += "difference is of " + second_diff / 86400 + " days.";
      } else if (second_diff < 31449600) {
         output.innerHTML += "difference is of " + second_diff / 2620800 + " months.";
      } else {
         output.innerHTML += "difference is of " + second_diff / 31449600 + " years.";
      }
   </script>
</body>
</html>

Use the RelativeTimeFormat() API of Intl

Intl refers to the internationalization API. It contains various methods for date and time formatting. We can use the RelativeTimeFormat() method of the Intl object to get the relative timestamp between two dates.

Syntax

Users can follow the syntax below to use the RelativeTimeFormat() API two get relative timestamp between two dates.

var relativeTimeStamp =
new Intl.RelativeTimeFormat("en", { numeric: "auto",});

// compare the value of RelativeTimeStamp with milliseconds of different time units

In the above syntax, the RelativeTimeFormat() method returns the timestamp difference. The time_Stamp_unit is an object containing the different time units with its total milliseconds.

Steps

Step 1 − Create an object of units that contains the time unit as a key and total milliseconds as a value for that time unit.

Step 2 − Get the time difference between two dates in milliseconds.

Step 3 − Now use the for-in loop to iterate through the time_stamp_unit object and check that the value of second_diff is greater than a total milliseconds of a particular time; use the format method of RelativeTimeFormat() API to format the timestamp in that particular unit.

Step 4 − Ater that, break the for-loop.

Example

In the example below, we have used the RelativeTimeFomrat() method to get the relative timestamp difference between two dates, as explained in the above syntax and steps.

<html>
<body>
   <h3>Getting the relative timestamp difference between two dates using the <i> RelativeTimeFormat() </i> method </h3>
   <p id="output"></p>
   <script>
      let output = document.getElementById("output");
      let current_date = new Date();
      let previous_date = new Date("jan 14, 2022 12:21:45");
      
      // finding the difference in total seconds between two dates 
      let second_diff = current_date.getTime() - previous_date.getTime();
      output.innerHTML += "The first date is " + current_date + "</br>";
      output.innerHTML += "The second date is " + previous_date + "</br>";
      var time_Stamp_unit = {
         year: 31536000000,
         month: 31536000000 / 12,
         day: 86400000,
         hour: 3600000,
         minute: 60000,
         second: 1000,
      };
      var relativeTimeStamp = new Intl.RelativeTimeFormat("en", {
         numeric: "auto",
      });
      
      // iterate through all time stamps
      for (var ele in time_Stamp_unit) {
         
         // if second_diff's value is greater than particular timesapm unit's total millisecond value, format accordingly
         if (Math.abs(second_diff) > time_Stamp_unit[ele] || ele == "second") {
            output.innerHTML += "The difference between two dates is " + relativeTimeStamp.format(
               Math.round(second_diff / time_Stamp_unit[ele]), ele
            );
            break;
         }
      }
   </script>
</body>
</html>

Users learned to find relative timestamps between two dates using the if-else statement and RelativeTimeFormat() API’s format() method. Users can use both approaches according to their requirements.

Updated on: 10-Mar-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements