Increment by day in JavaScript

I had a need to iterate over days of a year today in JavaScript.

I figured you could just add “one day” to the date, and that turns out to be true.

This is the test program I wrote to make sure the incrementing worked properly.

var year = 2008;

var endymd = new Date(year+1, 0, 1, 0, 0, 0);

var days = 0;
for (var ymd=new Date(year, 0, 1, 0, 0, 0);
    ymd<endymd; 
    ymd.setDate(ymd.getDate()+1)){
    days++;
}
console.log(days);

The answer is 366, which means that leap year was handled correctly.

Updated in 2015 (yes I use my old posts as notes to myself). Edited code to fix a bug, and also to use ymd&lt;endymd as the stopping condition. I used to do ymd.getDate()&lt;endymd, and defined endymd as getDate() from the get go. Probably the same speed, but a little cleaner to look at I think.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.