
Get days between two dates in JavaScript
Calculate days between two dates in JavaScript with a simple function. Learn how to handle DST issues and get accurate results.
To get the number of days between two given dates, you can do that by converting them to UTC timestamps and then computing the difference in days based on the millisecond difference. However, with the modern Temporal API, you have a more robust and readable alternative.
Modern approach using Temporal API
The Temporal API is a modern built-in solution for date and time manipulation in JavaScript. It’s designed to address the shortcomings of the legacy Date object. Here’s how to calculate days between two dates using Temporal:
function getDaysBetweenTwoDatesTemporal(firstDateInISO, secondDateInISO) {
const firstDate = Temporal.PlainDate.from(firstDateInISO);
const secondDate = Temporal.PlainDate.from(secondDateInISO);
// Calculate difference in days
const duration = firstDate.until(secondDate, { largestUnit: 'day' });
return Math.abs(duration.days);
}
// Example usage
console.log(getDaysBetweenTwoDatesTemporal('2024-03-01', '2024-03-10')); // 9
console.log(getDaysBetweenTwoDatesTemporal('2024-12-31', '2025-01-05')); // 5Note: The Temporal API is not available widely yet. For production use, consider a polyfill like @js-temporal/polyfill.
Legacy approach using traditional Date object
If you need to support older browsers, you can still use the traditional method with UTC timestamps. This approach handles Daylight Savings Time (DST) boundaries correctly by working in UTC.
function getDaysBetweenTwoDates(firstDateInISO, secondDateInISO) {
const startDate = new Date(firstDateInISO);
const endDate = new Date(secondDateInISO);
const firstDate = Date.UTC(startDate.getFullYear(), startDate.getMonth(), startDate.getDate());
const secondDate = Date.UTC(endDate.getFullYear(), endDate.getMonth(), endDate.getDate());
return Math.abs((firstDate - secondDate) / (24 * 60 * 60 * 1000));
}Simply subtracting the dates will not work over the Daylight Savings Time boundary (for example, April 1 to April 30 or October 1 to October 31). This reduces all of the hours to ensure you get a day and solves any DST issues by using UTC.
Why Temporal API is better
- No DST issues:
Temporal.PlainDateworks with calendar dates, not instants in time. - More readable: clear API methods like
until()express intent directly. - Immutable: all Temporal objects are immutable, preventing bugs.
- Timezone aware: handles timezones correctly with
ZonedDateTime. - Precise duration: returns proper duration objects with units like days, months, years.
Code explanation (legacy method)
Let’s break down the legacy code:
Input parameters:
firstDateInISO: a string representing the first date in ISO format.secondDateInISO: a string representing the second date in ISO format.
Date conversion:
- The code first converts the input date strings into
Dateobjects using thenew Date()constructor. - It then extracts the year, month, and date components from these
Dateobjects usinggetFullYear(),getMonth(), andgetDate()methods.
- The code first converts the input date strings into
Date comparison:
- The code converts the extracted year, month, and date components of both dates into UTC timestamps using
Date.UTC(). - These UTC timestamps are then used to calculate the difference in milliseconds between the two dates by subtracting the UTC timestamps and taking the absolute value.
- The code converts the extracted year, month, and date components of both dates into UTC timestamps using
Calculating days:
- The code divides the time difference in milliseconds by the total number of milliseconds in a day (24 hours * 60 minutes * 60 seconds * 1000 milliseconds) to get the number of days between the two dates.
- The result is returned as a number representing the absolute difference in days between the two input dates.
Practical example with unit tests for calculating days between dates
Here is a workable example that calculates days between two days and includes unit tests.
Comparison table
| Feature | Legacy Date | Temporal API |
|---|---|---|
| DST safe | ✅ (with UTC conversion) | ✅ |
| Readability | Medium | High |
| Immutability | ❌ | ✅ |
| First-class duration | ❌ | ✅ |
| Browser support | All | Modern only (needs polyfill) |
Comments