Home > Web Front-end > JS Tutorial > Get relative timestamp difference between dates in JavaScript

Get relative timestamp difference between dates in JavaScript

WBOY
Release: 2023-08-31 15:05:10
forward
1427 people have browsed it

在 JavaScript 中获取日期之间的相对时间戳差异

Have you ever seen a notification on any website showing a timestamp? It shows things like "12 minutes ago", "2 days ago", "10 hours ago" etc. It has to do with the timestamp difference between two dates or times.

Additionally, some apps show that the device was last logged in 22 hours ago. So getting the timestamp difference between two dates has many uses.

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

Use getTime() method with date and create custom algorithm

In JavaScript, we can use the new Date() constructor to create a date object. Additionally, we can pass a specific date as an argument to the Date() constructor to initialize a date object with that date value.

getTime() The method returns the total number of seconds since January 1, 1970. So we can find the total milliseconds of the two dates and then subtract them to get the millisecond difference. Using that millisecond, we can find the timestamp difference in seconds, minutes, years, etc.

grammar

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

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

In the above syntax, current_date and previous_date are two different dates. We use the getTime() method to get the millisecond difference between two dates.

Note - You can obtain relative timestamp differences by comparing the value of the second_diff variable to milliseconds.

step

Users can follow the steps below 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 of two dates and get the difference between them. Additionally, divide the millisecond difference by 1000 to convert it to seconds and store it in the secondary_diff variable.

Step 3 - Now, use if-else conditional statements to find relative timestamp differences.

Step 4 - If the value of second_diff is less than 60, the difference is in seconds. Second_diff has a value between 60 and 3600, with the difference in hours. Users can also calculate days, months, and years like this.

Example

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

In the output, the user can observe the timestamp difference of the month represented by the following code.

<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>
Copy after login

Use Intl's RelativeTimeFormat() API

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

grammar

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

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

// compare the value of RelativeTimeStamp with milliseconds of different time units
Copy after login

In the above syntax, the RelativeTimeFormat() method returns the timestamp difference. time_Stamp_unit is an object containing different time units and their total number of milliseconds.

step

Step 1 - Create a units object containing the time unit as the key and the total number of milliseconds as the value for that time unit.

Step 2 - Get the time difference (in milliseconds) between two dates.

Step 3 - Now use a for-in loop to iterate over the time_stamp_unit object and check if the value of second_diff is greater than the total number of milliseconds for a specific time; use RelativeTimeFormat() Use the format method of the API to format the timestamp in this specific unit.

Step 4 - After that, break the for loop.

Example

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

<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>
Copy after login

Users learned to find relative timestamps between two dates using if-else statements and RelativeTimeFormat() API's format() method. Users can use both methods according to their needs.

The above is the detailed content of Get relative timestamp difference between dates in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template