search
HomeWeb Front-endJS TutorialGet relative timestamp difference between dates in JavaScript

在 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; 

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 id="Getting-the-relative-timestamp-difference-between-two-dates-using-the-i-custom-algorithm-i">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 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

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 id="Getting-the-relative-timestamp-difference-between-two-dates-using-the-i-RelativeTimeFormat-i-method">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 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!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),