A simple example on how to loop between 2 dates in JavaScript

Here is the code to loop between 2 dates in JavaScript. To simplify the example, we will loop between today and next year.

Loop interval: 1 day

jsx
let today      = new Date();
let nextYear   = new Date(today.getFullYear() + 1, today.getMonth(), today.getDate()); 

for(let date = today; date <= nextYear; date.setDate(date.getDate() + 1)) {

    console.log(date);
    // Mon Feb 10 2020 12:40:19 GMT+0800
    // Tue Feb 11 2020 12:40:19 GMT+0800 
    // Wed Feb 12 2020 12:40:19 GMT+0800 
    // ...
    // Tue Feb 09 2021 12:40:19 GMT+0800

}

Loop interval: 1 month

jsx
let today      = new Date();
let nextYear   = new Date(today.getFullYear() + 1, today.getMonth(), today.getDate()); 

for(let date = today; date <= nextYear; date.setMonth(date.getMonth() + 1)) {

    console.log(date);
    // Mon Feb 10 2020 12:46:25 GMT+0800
    // Tue Mar 10 2020 12:46:25 GMT+0800
    // Fri Apr 10 2020 12:46:25 GMT+0800
    // ...
    // Sun Jan 10 2021 12:46:25 GMT+0800

}

Loop interval: 1 year

jsx
let today      = new Date();
let nextYear   = new Date(today.getFullYear() + 1, today.getMonth(), today.getDate()); 

for(let date = today; date <= nextYear; date.setYear(date.getFullYear() + 1)) {

    console.log(date);
    // Mon Feb 10 2020 12:46:25 GMT+0800

}

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.