How to calculate the number of days between two dates in JavaScript

I encountered a problem: how to calculate the number of days between two dates?

In particular, I want to calculate the number of days a person needs to pay for renting a room and sleeping in it, depending on the place of check-indate, And the checkout date.

I researched different solutions. Taking into account all date-related issues (including DST), the solution that brought me the least problems is: starting from the start date, we add one day until the date indicates the end date Date after.

This is 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 given date, because the date is an object, so we get areferenceThat object. This means usingsetDate()Variables in the function will also affect variables outside the function-not what we expect!

That's it.

If you want to get the number of days between two dates (for example, today to tomorrow is 2 days), you just need to changewhile (end > start)Towhile (end >= start). That works. Or increasedayCountstarting point1.

Download mine for freeJavaScript beginner's manual

More js tutorials: