How to Calculate Date Difference in JavaScript

Shraddha Paghdar Feb 02, 2024
How to Calculate Date Difference in JavaScript

This short article shows how to calculate the difference between two dates using JavaScript.

Calculate Date Difference in JavaScript

JavaScript Date objects represent a single point in time in a platform-independent format. Date objects contain a number representing milliseconds since January 1, 1970, UTC.

When a new Date() is called, it returns a new Date object. When Date() is called, it returns a string representation of the current date and time.

JavaScript provides various static methods like Date.now(), Date.parse() and Date.UTC(). Some of the instance methods are Date.prototype.getDate(), Date.prototype.getHours(), Date.prototype.getDay(), Date.prototype.getMilliseconds(), etc.

The dates must be converted to the Date objects to calculate the difference between two dates.

Code Example:

const date1 = new Date('04/13/2022');
const date2 = new Date('12/15/2022');
const diffInMS = Math.abs(date2 - date1);
const diffInDays = Math.ceil(diffInMS / (1000 * 60 * 60 * 24));
const diffInHours = Math.ceil(diffInMS / (1000 * 60 * 60));
console.log(diffInMS + ' milliseconds');
console.log(diffInDays + ' days');
console.log(diffInHours + ' hours');

We created two date instances in the example above.

This date instance contains the number of milliseconds since the epoch. You can first find out the difference in milliseconds.

Use Math.abs() function to eliminate the negative value. Once the difference in milliseconds is determined, you can calculate the difference in minutes, seconds, and hours by diving into the appropriate formula.

Output:

"21254400000 milliseconds"
"246 days"
"5904 hours"

Run Code

In this brief tutorial, we’ve learned to calculate the date difference using JavaScript. You can find more information about the date in this date documentation.

Shraddha Paghdar avatar Shraddha Paghdar avatar

Shraddha is a JavaScript nerd that utilises it for everything from experimenting to assisting individuals and businesses with day-to-day operations and business growth. She is a writer, chef, and computer programmer. As a senior MEAN/MERN stack developer and project manager with more than 4 years of experience in this sector, she now handles multiple projects. She has been producing technical writing for at least a year and a half. She enjoys coming up with fresh, innovative ideas.

LinkedIn

Related Article - JavaScript Date