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);

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 Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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