Skip to content

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

New Course Coming Soon:

Get Really Good at Git

I had this problem: how do I calculate the number of days between 2 dates?

In particular, 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.

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!

That’s it.

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.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Get my JavaScript Beginner's Handbook
→ Read my JavaScript Tutorials on The Valley of Code
→ Read my TypeScript Tutorial on The Valley of Code

Here is how can I help you: