How to Generate Dates Between Two Dates in JavaScript

To generate dates between two dates in JavaScript, you can 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.

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
]

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 lines inside the while loop.

That’s it!

Leave a Comment