difference between two dates in javascript

How to Get Difference Between Two Dates in JavaScript

Almost every website needs to work with dates in one way or the other. JavaScript provides tons of features to use dates and manipulate them as per your requirements. Often web developers need to get difference between two dates in JavaScript. In this article, we will learn how to get difference between two dates in JavaScript.


How to Get Difference Between Two Dates in JavaScript

Let us say you have the following dates in JavaScript.

date1 = new Date('7/13/2022');
date2 = new Date('12/15/2022');

There are several ways to calculate date difference in JavaScript. We will look at a couple of simple methods to do this.

You can easily get the difference in dates, in milliseconds, by subtracting one date from the other.

diffTime = Math.abs(date2 - date1);

If you want to calculate the date difference in seconds, divide the above number by 1000.

If you want to calculate the difference in two dates, in number of days, then divide the result of above difference by 1000 * 60 * 60 * 24.

diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); 

However, if your two dates span a daylight saving timezone, then you need to convert both the dates to UTC (Universal Coordinated Time) and then take the difference.

utc1 = Date.UTC(date1.getFullYear(), date1.getMonth(), date1.getDate());
utc2 = Date.UTC(date2.getFullYear(), date2.getMonth(), date2.getDate());

Then you need to take the difference in two dates to get information in milliseconds.

time_diff = Math.abs(utc2 - utc1)

If you need the date difference in number of days, then divide the above value by 1000 * 60 * 60 *24.

days_diff = Math.floor((utc2 - utc1) / 1000*60*60*24)

You can use Math.floor() or Math.ceil() depending on your requirement.

In this article, we have learnt a couple of ways to calculate difference between two dates. You can use either of them as per your need.

Also read:

How to Shuffle Array in JavaScript
How to Dynamically Create Variables in Python
How to Login to PostgreSQL Without Password
How to Store PostgreSQL Output to File
How to Get Row Count For All Tables in MySQL

Leave a Reply

Your email address will not be published. Required fields are marked *