How to Loop Through a Date Range with JavaScript?

image

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.

Using a while Loop

One way to loop through a date range with JavaScript is to use a while loop.

We can create variables for the start and end dates.

Then we can increment the start date until it reaches the end date.

To do this, we 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);
  let newDate = loop.setDate(loop.getDate() + 1);
  loop = new Date(newDate);
}

We have the start and end variables with the start and end date respectively.

Then we create the loop variable that we use as the looping variable.

We increment the date of loop until it reaches end .

We do the incrementing by calling setDate with the loop.getdate() + 1 .

getDate lets us get the day of the month.

We assign the returned date to loop to increment it.

Therefore, we get:

Wed Feb 05 2020 00:00:00 GMT-0800 (Pacific Standard Time)
Thu Feb 06 2020 00:00:00 GMT-0800 (Pacific Standard Time)
Fri Feb 07 2020 00:00:00 GMT-0800 (Pacific Standard Time)
Sat Feb 08 2020 00:00:00 GMT-0800 (Pacific Standard Time)
Sun Feb 09 2020 00:00:00 GMT-0800 (Pacific Standard Time)
Mon Feb 10 2020 00:00:00 GMT-0800 (Pacific Standard Time)

from the console log.

Conclusion

We can loop through a date range with a while loop with a looping variable that’s set to the start date.

Then we increment the looping variable until it reaches the end date.

Enjoyed this article?

Share it with your network to help others discover it

Continue Learning

Discover more articles on similar topics