Sometimes, we want to loop through a date range with JavaScript.
In this article, we’ll look at how to loop through a date range with JavaScript.
Loop Through a Date Range with JavaScript
To loop through a date range with JavaScript, we can use a while loop.
For instance, we can write:
const start = new Date("02/05/2020");
const end = new Date("02/10/2020");
let loop = new Date(start);
while (loop <= end) {
console.log(loop);
const newDate = loop.setDate(loop.getDate() + 1);
loop = new Date(newDate);
}
We create the start
and end
date objects that are the start and end dates of the date range.
loop
is the variable with the start
date.
We increment loop
in the while loop until it’s bigger than or equal to end
.
To do that, we write:
const newDate = loop.setDate(loop.getDate() + 1);
loop = new Date(newDate);
Therefore, we see the dates in the date range being looped through and logged to the console.
Conclusion
To loop through a date range with JavaScript, we can use a while loop.