JavaScript
Date Difference
Web Development
Programming
Coding

Get difference between 2 dates in JavaScript?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

In JavaScript, calculating the difference between two dates is a common task encountered in many web development scenarios, from checking how long a user has been registered on a site to powering countdown clocks. To achieve this, JavaScript provides a straightforward approach leveraging the Date object. Below we will explore how to calculate the difference between two dates, various nuances associated with it, and some practical examples.

Understanding the Date Object in JavaScript

The JavaScript Date object represents a single moment in time in a platform-independent format. Date objects contain a Number that represents milliseconds since 1 January 1970 UTC.

Creating a date object can be done in various ways:

javascript
let date1 = new Date(); // current date and time
let date2 = new Date("2023-01-01"); // specific date

Calculating the Difference

To find the difference between two dates, you subtract one Date object from another, which gives you the difference in milliseconds. This result can then be converted into a more understandable unit like hours, days, or years.

Example:

javascript
1const date1 = new Date("2023-01-01");
2const date2 = new Date("2024-01-01");
3
4const differenceInMilliseconds = date2 - date1;
5const differenceInSeconds = differenceInMilliseconds / 1000;
6const differenceInMinutes = differenceInSeconds / 60;
7const differenceInHours = differenceInMinutes / 60;
8const differenceInDays = differenceInHours / 24; 

Handling Time Zones

When working with dates, particularly across different locales or time zones, you might get unexpected results due to the local time zone being applied.

To deal with time zone issues, always use UTC dates when comparing:

javascript
const date1 = new Date(Date.UTC(2023, 0, 1)); // Jan 1, 2023
const date2 = new Date(Date.UTC(2024, 0, 1)); // Jan 1, 2024

Leap Years and Other Considerations

While calculating differences in days or larger units, consider variations like leap years or daylight saving changes. Months also vary in length, which can affect calculations when considering months or years difference.

Summary Table

The following table summarizes the conversions used to compute time differences from milliseconds:

UnitDivision Factor
Milliseconds1
Seconds1,000
Minutes60,000
Hours3,600,000
Days86,400,000

Advanced Usage: Time Interval Functions

For a more human-friendly approach, rather than manual calculations, the Internationalization API provides Intl.RelativeTimeFormat. This API allows localized formatting of relative time phrases (e.g., "in 3 months" or "2 days ago").

Example:

javascript
1const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
2const daysDifference = Math.round(differenceInDays);
3
4console.log(rtf.format(-daysDifference, 'day'));

Conclusion

Calculating the difference between two dates in JavaScript is straightforward once you handle the milliseconds conversion and consider time zone complexities. By using either the native Date methods or more sophisticated internationalization APIs, developers can handle even the most complex time-related tasks in their applications.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.