Search code examples
javascriptdatefor-loopinfinite-loopinfinite

Javascript for loop with date


I am trying to iterate over every day in a month, but my for loop gets stuck (into endless mode):

var today = new Date();
var numberOfDaysInMonth = new Date( today.getFullYear(), lastMonth, 0 ).getDate();

...

for ( var date = new Date( today.getFullYear(), lastMonth, 1 ); date.getDate() <= numberOfDaysInMonth; date.setDate( date.getDate()+1 ) ) {

...

All the seperate parts of the for-loop arguments work as expected. If I replace the "<=" with just "<" in the condition the loop also runs, but ofcourse stops too early.

Does someone have any idea what might drive this loop into infinity? I'm clueless...


Solution

  • date.setDate( date.getDate()+1 )
    

    When date.setDate(31 + 1) is called, the day is reset to 0 and the month is advanced by 1, because that's the "next" date.

    Instead, loop like this:

    var begin = new Date("4 februari 2014");
    var end = new Date("4 march 2014");
    
    for (;begin < end; begin.setDate(begin.getDate()+1)) {
        console.log(begin);
    }
    

    This will display the dates between 4 februari and 4 march.