Skip to content

How to get the days between 2 dates in JavaScript

New Course Coming Soon:

Get Really Good at Git

Given two JavaScript `Date` objects, how can I get a list of the days (expressed as Date objects, too) between those 2 dates?

I had this problem: given two JavaScript Date objects, how can I get a list of the days (expressed as Date objects, too) between those 2 dates?

Here’s a function to calculate that.

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
}

Example usage:

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

getDatesBetweenDates(today, threedaysFromNow)

If you also want to include the start and end dates, 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
}
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: