Get relative timestamp difference between dates in 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>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>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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

This article explores effective use of Java's Collections Framework. It emphasizes choosing appropriate collections (List, Set, Map, Queue) based on data structure, performance needs, and thread safety. Optimizing collection usage through efficient

This tutorial will explain how to create pie, ring, and bubble charts using Chart.js. Previously, we have learned four chart types of Chart.js: line chart and bar chart (tutorial 2), as well as radar chart and polar region chart (tutorial 3). Create pie and ring charts Pie charts and ring charts are ideal for showing the proportions of a whole that is divided into different parts. For example, a pie chart can be used to show the percentage of male lions, female lions and young lions in a safari, or the percentage of votes that different candidates receive in the election. Pie charts are only suitable for comparing single parameters or datasets. It should be noted that the pie chart cannot draw entities with zero value because the angle of the fan in the pie chart depends on the numerical size of the data point. This means any entity with zero proportion
