Determining the number of days between two dates is a common requirement in many JavaScript applications. Whether you‘re building a scheduling app, calculating employee tenure, or just want to know how many days until your next vacation, JavaScript makes date math easy.
In this comprehensive guide, we‘ll explore several methods to calculate the difference between two dates in JavaScript.
Overview
At a high level, here are the steps to calculate days between dates in JavaScript:
- Create
Dateobjects from your start and end dates - Get timestamp values from the
Dateobjects withgetTime() - Subtract the timestamps to get the difference in milliseconds
- Convert milliseconds to days by dividing by number of milliseconds per day
Now let‘s look at how to implement this in JavaScript.
Convert Dates to Timestamps
To perform math on dates, we first need to convert them to numeric timestamps using the Date object.
Here‘s an example creating two Date objects:
const startDate = new Date(‘2023-03-01‘);
const endDate = new Date(‘2023-03-15‘);
The Date constructor accepts date strings, timestamps, year/month/day arguments, and more. Once we have Date objects, we can get numeric timestamps using the getTime() method:
const startTs = startDate.getTime(); // 1677664000000
const endTs = endDate.getTime(); // 1678867200000
getTime() returns the number of milliseconds since January 1, 1970 UTC, perfect for math operations.
Now we can subtract the two timestamps to find the difference:
const diffInMs = endTs - startTs; // 1209600000
With the timestamps converted to a readable number, we can now convert this duration into days.
Convert Milliseconds to Days
To convert our difference in milliseconds to days, we simply divide by the number of milliseconds in a day.
const millisecondsPerDay = 1000 * 60 * 60 * 24; // 86400000
const diffInDays = diffInMs / millisecondsPerDay; // 14
And there we have it — the difference between the two dates in days!
Let‘s put it all together into a reusable getDaysBetweenDates() function:
function getDaysBetweenDates(startDate, endDate) {
// Convert to timestamps
const startTs = startDate.getTime();
const endTs = endDate.getTime();
// Calculate difference in milliseconds
const diffInMs = endTs - startTs;
// Convert back to days and return
const millisecondsPerDay = 1000 * 60 * 60 * 24;
const diffInDays = Math.round(diffInMs / millisecondsPerDay);
return diffInDays;
}
To use it:
const days = getDaysBetweenDates(new Date(‘2023-03-01‘), new Date(‘2023-03-15‘));
// days = 14
Clean, reusable, and easy to understand!
Rounding the Result
When converting milliseconds to days, you may end up with fractional days as shown below:
const daysBetween = diffInMs / millisecondsPerDay;
// daysBetween = 14.157...
To get an whole number, use Math.round(), Math.floor() or Math.ceil() to round it appropriately:
const daysBetween = Math.round(diffInMs / millisecondsPerDay); // 14
const daysBetween = Math.ceil(diffInMs / millisecondsPerDay); // 15
Accounting for Timezones
One complexity that arises when working with dates is timezones.
For example, if you create a date string like ‘2023-03-15‘ in Los Angeles, and create another like ‘2023-03-15‘ in India, they will result in different points in time.
To eliminate timezone ambiguity, the best practice is to specify dates in UTC:
new Date(‘2023-03-15T00:00:00.000Z‘)
This creates a timestamp at midnight UTC, unaffected by timezone offsets.
So our final getDaysBetweenDates() function handles timezones:
function getDaysBetweenDates(startDate, endDate) {
// Convert to UTC timestamps
startDate = new Date(startDate.toISOString());
endDate = new Date(endDate.toISOString());
// Rest of logic...
}
Now you can pass in dates from any timezone and get the correct difference.
Alternative: Day.js Library
As we‘ve seen, native date handling in JavaScript can get quite complex with timezones, formatting, etc.
An alternative is to use a date library like Day.js to simplify the code:
import dayjs from ‘dayjs‘;
function getDaysBetweenDates(start, end) {
const diff = dayjs(end).diff(start, ‘days‘);
return Math.abs(diff);
}
Day.js handles parsing date strings, timestamps and Date objects automatically in a predictable timezone-aware manner. We simply diff the end and start dates, then return the absolute value of days between.
For more complex date calculations, date libraries are certainly worth considering.
Additional Examples
Here are some additional examples of using this getDaysBetweenDates() function in real-world situations:
Employee Tenure
const employeeStart = new Date(‘2020-01-01‘);
const today = new Date();
const tenure = getDaysBetweenDates(employeeStart, today) / 365;
console.log(`Employee has ${tenure.toFixed(2)} years of tenure`);
// Employee has 3.24 years of tenure
Date Range Selection
const start = new Date(‘2023-03-01‘);
const end = new Date(‘2023-03-15‘);
const selection = `${start.toDateString()} - ${end.toDateString()}`;
const daysSelected = getDaysBetweenDates(start, end);
console.log(`Selected ${daysSelected} over date range ${selection}`);
// Selected 14 over date range Wed Mar 01 2023 - Wed Mar 15 2023
This could be used to display a selected date range picker, calculate pricing over the selection, enforce business date rules, etc.
As you can see, calculating days between dates opens up useful abilities across applications!
Common Issues and Solutions
Here are some common issues faced when calculating days between dates in JavaScript:
Passing Invalid Dates
If invalid dates are passed to the Date constructor, it will try to make sense of it and possibly return unexpected results:
new Date(‘random‘); // Date: Invalid Date
new Date(‘2023-15-32‘); // Date: NaN
To safeguard against this, validate inputs with a library like date-fns or throw errors for invalid dates.
Daylight Savings Time Offsets
Working across Daylight Savings Time transitions can cause +/- 1 hour differences that may be unexpected when calculating days.
This can be avoided by using UTC timestamps as shown earlier.
Browser Compatibility
While native JavaScript dates are supported across environments, they do have many browser quirks and inconsistencies in parsing strings, localization, and more.
For consistent behavior across browsers, use a date library or polyfill certain functionality that differs.
With good validation and timezone handling, these issues can be prevented.
Conclusion
Calculating the number of days between two JavaScript dates is a useful technique for everything from travel planning to timecards to age calculations.
As we learned, here are best practices when finding days between dates:
- Convert dates to timestamps with
DateandgetTime() - Handle timezone ambiguity by using the UTC methods or libraries
- Validate date inputs before date math
- Use millisecond conversions for precision date differences
- Round to whole numbers if needed
Implementing this date difference logic in a reusable function provides clean readable code. Additional libraries like Day.js can simplify many date operations as well.
Date math is fundamental across countless applications. I hope this guide gave you a comprehensive overview of the options, considerations, and implementation in JavaScript.
Now go forth and safely subtract some JavaScript dates!


