Monday, January 29, 2007

Feature or annoyance?

There are a lot of birthdays to track for our family. The current webpage I use has 76 friends and family on there. For the techies, it's a javascript page that dynamically generates those birthdays coming up in the next 3 weeks so we can keep track. There's been a random bug that's been driving me nutz, every so often birthdays would stop showing up.

Today is a good example, there are 7 birthdays in the next 3 weeks, and none of them are being listed. See if you can spot the bug:
birthDay = new Date();
dateInfo = birthdays[idx][1].split("-");

// Internal JS representation is 0-11 not 1-12!
birthDay.setMonth(dateInfo[0]-1);
birthDay.setDate(dateInfo[1]);
The birthdays array contains two items, a name and a birthday represented as MM-DD. Everything is well formed in the source data and loads properly. However, on days like today it fails. Take a minute, I wont make you suffer long...

If you figured it, skip the following explanation;

It has to do with the Date class in Javascript. As it turns out, Date will not let you set a new month into it such that the existing day in that Date object is invalid.

In the code above, when the object is created it gets today's date; Jan 29 2007. When you try to do the SetMonth for February, it fails as February of this year cannot have 29 days. However, it does push the month to March, which can. Not sure why it pushes to March, but it does. This resulted in all the February birthdays I had "mystically" going away for a little while, then coming back.

The fix? Do a birthDay.setDate(1) to force it to a day we know all months have and everything works as expected.

No comments: