Calculate the number of days between 2 dates in JavaScript
By Flavio Copes
Learn how to calculate the number of days or nights between two dates in JavaScript by adding a day at a time in a loop, an approach that handles DST safely.
To count the days between two dates in JavaScript, clone the start date and add one day at a time until you pass the end date. Count the iterations, and that’s your number of days.
I needed this for a booking system. I wanted to count the number of nights that a person had to pay to rent a house and sleep in it, depending on the checkin date, and the checkout date.
Why not just subtract the two dates?
The first instinct is to subtract the timestamps and divide by the milliseconds in a day:
const days = (end - start) / (1000 * 60 * 60 * 24)
This works most of the time. But not every day is 24 hours long.
When daylight saving time starts, one day lasts 23 hours. When it ends, one day lasts 25 hours. Cross one of those days and the division returns something like 4.958333, and now you have to guess how to round it.
The loop approach
I looked at different solutions, and the one that gave me the least problems, considering all the issues with dates (including DST), was this: starting from the starting date, we add one day until the date represents a date after the end date.
Here’s the code:
const numberOfNightsBetweenDates = (startDate, endDate) => {
const start = new Date(startDate) //clone
const end = new Date(endDate) //clone
let dayCount = 0
while (end > start) {
dayCount++
start.setDate(start.getDate() + 1)
}
return dayCount
}
I first clone the dates we are given, because dates are objects, and we get a reference to that object. This means that using setDate() in the function would also affect the variable outside of this function - not something we look forward to!
setDate() knows about DST, so a 23-hour or 25-hour day still counts as one day.
Here it is in action:
numberOfNightsBetweenDates(new Date(2026, 7, 10), new Date(2026, 7, 15)) //5
If instead you want to get the number of days between 2 dates (say, today to tomorrow is 2 days), just change while (end > start) to while (end >= start). That would work. Or increase the dayCount starting point to 1.
Watch out for date strings
There’s one trap. A date-only string like '2026-03-28' is parsed as UTC midnight, not local midnight.
If your timezone changes its UTC offset between the two dates (a DST switch), the two dates sit at different local wall-clock times, and the count comes out one too high.
The fix is to normalize both clones to local midnight, right after cloning:
start.setHours(0, 0, 0, 0)
end.setHours(0, 0, 0, 0)
This also handles dates that carry a time of day, like a 22:00 checkin and a 10:00 checkout. After normalizing, only the calendar dates matter.
If you just need a quick answer without writing code, try the date duration calculator.
Related posts about js: