Get all Dates between 2 Dates using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Get all Dates between 2 Dates using JavaScript #

To get all of the dates between 2 dates:

  1. Create an array that will store the Date objects.
  2. Iterate over the dates in the range.
  3. Push each Date object to the dates array.
index.js
function getDatesInRange(startDate, endDate) { const date = new Date(startDate.getTime()); const dates = []; while (date <= endDate) { dates.push(new Date(date)); date.setDate(date.getDate() + 1); } return dates; } const d1 = new Date('2022-01-18'); const d2 = new Date('2022-01-24'); console.log(getDatesInRange(d1, d2));

Note: the function above includes the start and end dates in the results array.

If you want to exclude the end date, you can change the line where we used the while loop to while (date < endDate) {. Changing the less than or equals to to less than excludes the end date from the results.

If you want to exclude the start date as well, use this code snippet instead:

index.js
function getDatesInRange(startDate, endDate) { const date = new Date(startDate.getTime()); // ✅ Exclude start date date.setDate(date.getDate() + 1); const dates = []; // ✅ Exclude end date while (date < endDate) { dates.push(new Date(date)); date.setDate(date.getDate() + 1); } return dates; } const d1 = new Date('2022-01-18'); const d2 = new Date('2022-01-24'); console.log(getDatesInRange(d1, d2));

We manually added 1 day to exclude the start date from the results.

The getDatesInRange function takes a start and end dates as parameters and returns an array containing all of the dates between them.

We created a Date object that is a clone of startDate because the setDate() method mutates the Date object in place and it's not a good practice to mutate function arguments.

The dates array is there to store all of the Date objects in the range.

We used a while loop to iterate over the dates in the range, as long as the start date is less than or equal to the end date.

When you compare Date objects, they implicitly get converted to a timestamp of the time elapsed between the Unix Epoch (1st of January, 1970) and the given date.

The setDate method changes the day of the month for the given Date instance in place.

On each iteration, we set the start date to the next date until the start date reaches the end date.

Once the start date reaches the end date, the condition in the while loop is no longer met and the dates array is returned from the function.
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.