user3325748
user3325748

Reputation: 43

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...

Upvotes: 4

Views: 1446

Answers (2)

Will P.
Will P.

Reputation: 8787

The date object cannot setDate beyond the latest day in the month. It will always be less than or equal to the maximum getDate() value.

Upvotes: 3

Bart
Bart

Reputation: 27205

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.

Upvotes: 1

Related Questions