How to Calculate the Time Difference Between Two Dates in JavaScript
Calculating the duration between two dates is a fundamental task in JavaScript. You might need to find the number of days until a deadline, the age of a user in years, or the number of hours spent on a task. The approach you take depends on the unit of time you need, as calculating days is different from calculating months.
This guide will teach you the two primary methods for calculating date differences. You will learn the timestamp subtraction method, which is perfect for fixed-size units like days, hours, and minutes. You will also learn the date component method, which is essential for handling variable-size units like months and years.
Core Concept: Millisecond Timestamps
The foundation for most date calculations in JavaScript is the Unix timestamp. This is the number of milliseconds that have elapsed since January 1, 1970, 00:00:00 UTC. You can get this value from any Date object using the .getTime() method.
Crucially, when you subtract one Date object from another, JavaScript automatically calls .getTime() on both, giving you the difference between them in milliseconds.
const date1 = new Date('2023-10-26');
const date2 = new Date('2023-10-27');
const differenceInMs = date2 - date1; // or date2.getTime() - date1.getTime()
console.log(differenceInMs); // Output: 86400000
This millisecond difference is the starting point for calculating all fixed-duration units.
Calculating Differences for Fixed-Duration Units
Units like days, hours, and minutes always have a fixed number of milliseconds. This allows us to use a simple formula:
differenceInUnit = differenceInMs / millisecondsInOneUnit
Get the Difference in Days
The logic:
- Calculate the difference between the two dates in milliseconds.
- Define the number of milliseconds in one day (
1000 * 60 * 60 * 24). - Divide the total millisecond difference by the number of milliseconds in a day.
Example:
function getDifferenceInDays(date1, date2) {
const diffInMs = Math.abs(date2 - date1);
return diffInMs / (1000 * 60 * 60 * 24);
}
const days = getDifferenceInDays(new Date('2023-10-01'), new Date('2023-10-21'));
console.log(Math.round(days)); // Output: 20
Math.abs(): Ensures the result is always a positive number, regardless of which date is earlier.Math.round(): Rounds the result to the nearest whole number to account for daylight saving time or fractional days.
Get the Difference in Hours, Minutes, and Seconds
The same logic applies, but with different divisors.
function getDifferenceInHours(date1, date2) {
const diffInMs = Math.abs(date2 - date1);
return diffInMs / (1000 * 60 * 60);
}
function getDifferenceInMinutes(date1, date2) {
const diffInMs = Math.abs(date2 - date1);
return diffInMs / (1000 * 60);
}
function getDifferenceInSeconds(date1, date2) {
const diffInMs = Math.abs(date2 - date1);
return diffInMs / 1000;
}
Get the Difference in Weeks
Simply extend the "days" logic.
function getDifferenceInWeeks(date1, date2) {
const diffInMs = Math.abs(date2 - date1);
return diffInMs / (1000 * 60 * 60 * 24 * 7);
}
const weeks = getDifferenceInWeeks(new Date('2023-10-01'), new Date('2023-10-22'));
console.log(Math.round(weeks)); // Output: 3
Calculating Differences for Variable-Duration Units
Units like months and years do not have a fixed number of days. A month can be 28, 29, 30, or 31 days long, and a year can be 365 or 366. For these, simple millisecond division is not accurate. We must use the Date object's built-in methods to compare the components directly.
Get the Difference in Months
Calculate the difference in years, multiply by 12, and then add the difference in months.
function getDifferenceInMonths(date1, date2) {
const yearDiff = date2.getFullYear() - date1.getFullYear();
const monthDiff = date2.getMonth() - date1.getMonth();
return (yearDiff * 12) + monthDiff;
}
const months1 = getDifferenceInMonths(new Date('2023-01-15'), new Date('2023-05-20'));
console.log(months1); // Output: 4
const months2 = getDifferenceInMonths(new Date('2022-10-10'), new Date('2023-05-20'));
console.log(months2); // Output: 7
Get the Difference in Years
There are two common ways to calculate the difference in years, depending on your needs.
Simple Calendar Year Difference
This is the easiest but least precise method.
function getCalendarYearDifference(date1, date2) {
return Math.abs(date2.getFullYear() - date1.getFullYear());
}
// Even though it's less than a year, the calendar year changed.
console.log(getCalendarYearDifference(new Date('2022-12-31'), new Date('2023-01-01'))); // Output: 1
Calculating Age in Whole Years (More Precise)
This is the correct method for calculating a person's age or the number of full years that have passed.
function getAgeInYears(startDate, endDate) {
let yearDiff = endDate.getFullYear() - startDate.getFullYear();
let monthDiff = endDate.getMonth() - startDate.getMonth();
let dayDiff = endDate.getDate() - startDate.getDate();
// If the end date is earlier in the year than the start date, subtract a year
if (monthDiff < 0 || (monthDiff === 0 && dayDiff < 0)) {
yearDiff--;
}
return yearDiff;
}
// The 25th birthday has not happened yet in 2024
const age = getAgeInYears(new Date('1999-10-27'), new Date('2024-05-15'));
console.log(age); // Output: 24
Conclusion
Calculating the time between two dates in JavaScript requires choosing the right method for the unit you need.
- For fixed-duration units (days, hours, minutes, seconds), the best practice is to subtract the
Dateobjects to get the difference in milliseconds and then divide by the appropriate constant. - For variable-duration units (months, years), you must use the
Dateobject's component methods likegetFullYear()andgetMonth()to perform the calculation accurately.