How to get the days between 2 dates in JavaScript

By

Learn how to get every day between two dates in JavaScript with a function that loops from the start, adding a day at a time, and returns an array of Dates.

~~~

To get all the days between two JavaScript Date objects, loop from the start date, add one day at a time with setDate(), and collect each day into an array.

I had this exact problem while building a habit tracker: given two dates, I needed the full list of days in between, each one as a Date object, so I could render one row per day.

Here’s the function. It gets 2 date objects as parameters, and returns an array of Date objects:

const getDatesBetweenDates = (startDate, endDate) => {
  let dates = []
  //to avoid modifying the original date
  const theDate = new Date(startDate)
  while (theDate < endDate) {
    dates = [...dates, new Date(theDate)]
    theDate.setDate(theDate.getDate() + 1)
  }
  return dates
}

How does it work?

The first thing we do is copy the start date with new Date(startDate). This matters. setDate() mutates the date it’s called on, so without the copy we would change the caller’s original object. That’s a bug you notice much later, far from this function.

Then the loop runs while theDate is before endDate. On each pass we push a new Date into the array, again to get an independent copy, and then move theDate one day forward.

setDate() handles month and year rollovers for us. If the loop reaches January 31 and adds a day, we get February 1, not January 32. It also handles daylight saving time changes, which is why adding days this way is safer than adding 86400 seconds worth of milliseconds to a timestamp.

Example usage:

const today = new Date()
const threedaysFromNow = new Date(today)
threedaysFromNow.setDate(threedaysFromNow.getDate() + 3)

getDatesBetweenDates(today, threedaysFromNow)

If today is August 7, this returns the dates for August 7, 8 and 9.

What about the end date?

Notice the end date is excluded, because the loop stops as soon as theDate reaches it. That surprised me the first time.

If you also want to include the end date, you can use this version that adds it at the end:

const getDatesBetweenDates = (startDate, endDate) => {
  let dates = []
  //to avoid modifying the original date
  const theDate = new Date(startDate)
  while (theDate < endDate) {
    dates = [...dates, new Date(theDate)]
    theDate.setDate(theDate.getDate() + 1)
  }
  dates = [...dates, endDate]
  return dates
}

One edge case to keep in mind: if startDate is after endDate, the loop never runs and you get an empty array (or just the end date, in the inclusive version). If that can happen in your app, check the order before calling the function.

If you just need the number of days between two dates, you can use the date duration calculator.

~~~

Related posts about js: