How to Generate Dates Between Two Dates in JavaScript

To generate dates between two dates in JavaScript, use the setDate() and getDate() functions. The setDate() is a built-in JavaScript method that sets the day of the month of a date. The getDate() is a built-in method that returns the day of the month (1 to 31) of a date.

There are certain cases when we need to find out all dates between two given dates. E.g., let’s say we have a given date, and we need to find the date 3 days after the given date or 400 days after the given date, so in such scenarios, we need to find dates in between to get the desired result. Let’s understand the concept by some examples:

Example Source Code

function getDatesBetween(startDate, endDate) {
  const currentDate = new Date(startDate.getTime());
  const dates = [];
  while (currentDate <= endDate) {
    dates.push(new Date(currentDate));
    currentDate.setDate(currentDate.getDate() + 1);
  }
  return dates;
}

const date1 = new Date('2022-04-15');
const date2 = new Date('2022-04-30');

let allDates = getDatesBetween(date1, date2);
console.log(allDates);

Output

[
  2022-04-15T00:00:00.000Z,
  2022-04-16T00:00:00.000Z,
  2022-04-17T00:00:00.000Z,
  2022-04-18T00:00:00.000Z,
  2022-04-19T00:00:00.000Z,
  2022-04-20T00:00:00.000Z,
  2022-04-21T00:00:00.000Z,
  2022-04-22T00:00:00.000Z,
  2022-04-23T00:00:00.000Z,
  2022-04-24T00:00:00.000Z,
  2022-04-25T00:00:00.000Z,
  2022-04-26T00:00:00.000Z,
  2022-04-27T00:00:00.000Z,
  2022-04-28T00:00:00.000Z,
  2022-04-29T00:00:00.000Z,
  2022-04-30T00:00:00.000Z
]

Explanation

In this example, we created a function named getDatesBetween() which takes two parameters, startDate, and endDate. There are two dates between them we need to print all the dates. After that, we create a date object from startDate. And assign it to a new currentDate variable.

We created a “dates” array which will contain all the dates between the given two dates. Now we are doing the rest of the work inside the while loop with the condition that the currentDate should be less than or equal to the endDate. As soon as the condition is true the currentDate value is pushed inside the dates array.

After pushing the currentDate value we are incrementing the date with 1 (currentDate.setDate(currentDate.getDate() + 1)). This loop will execute till the endDate and then the function will return the dates array. Finally, we are printing the dates using the console.log() function.

Note: In this example, startDate and endDate are included in the final dates. If you want to exclude endDate from them, make sure to change the while condition from (currentDate <= endDate) to (currentDate < endDate) and swap both the lines inside the while loop.

That’s it for this tutorial.

More tutorials

How to Convert Date to String in JavaScript

How to Format Dates in JavaScript

Convert TimeStamp to Date in JavaScript

Leave a Comment