In JavaScript, to get all dates between 2 given dates as an array, we can use a loop to iterate over the dates and push each date to an array until we reach the end date. We can use the push() method to add the dates to the array.
This example finds and displays all dates between March 1, 2023, and March 7, 2023:
// start date
const startDate = new Date('2023-03-01');
// end date
const endDate = new Date('2023-03-87');
// array of dates
const datesArray = [];
// loop from start date to end date
for (
let date = startDate;
date <= endDate;
date.setDate(date.getDate() + 1)
)
{
datesArray.push(new Date(date));
}
console.log(datesArray);
Output:
[
Wed Mar 01 2023 00:00:00 GMT-0800 (Pacific Standard Time),
Thu Mar 02 2023 00:00:00 GMT-0800 (Pacific Standard Time),
Fri Mar 03 2023 00:00:00 GMT-0800 (Pacific Standard Time),
Sat Mar 04 2023 00:00:00 GMT-0800 (Pacific Standard Time),
Sun Mar 05 2023 00:00:00 GMT-0800 (Pacific Standard Time),
Mon Mar 06 2023 00:00:00 GMT-0800 (Pacific Standard Time),
Tue Mar 07 2023 00:00:00 GMT-0800 (Pacific Standard Time)
]
We can also refine the code above and create a reusable function like this:
const getDatesBetween = (startDate, endDate) => {
let dates = [];
let currentDate = new Date(startDate);
while (currentDate <= endDate) {
dates.push(new Date(currentDate));
currentDate.setDate(currentDate.getDate() + 1);
}
return dates;
};
// try it
const result = getDatesBetween(
new Date('2023-03-01'),
new Date('2023-03-07')
);
console.log(result);
And we’ll get the same output as the preceding code.
Getting all dates between 2 given dates in JavaScript has some real-world use cases, such as:
- Booking Dates: When a user is booking a hotel or reserving a spot for an event online, the website can use this technique to show all available dates between a selected range, so the user can choose the appropriate date.
- Planning & Project Management: When a project manager needs to create a schedule for a project with a start and end date, this method can be used to generate an array of all the dates in between. The dates can be used to assign tasks, track progress, and set deadlines.
Hope this helps. Happy coding & have a nice day!