> date = new Date(2013, 0, 1) Tue Jan 01 2013 00:00:00 GMT+1100 (EST) > date.setUTCMonth(10)
First, I create a new date at midnight on January 1, 2013 (yes, months start from 0 and dates start from 1, it’s insane). Then, I set the month to November. What is the resulting value of date? Surely it’s November 01 2013? Nope, it’s:
Sun Dec 02 2012 00:00:00 GMT+1100 (EST)
Wat? The month is one year earlier, one month later, and one day later than I had expected. But it gets worse:
> date.setUTCMonth(10) Fri Nov 02 2012 00:00:00 GMT+1100 (EST)
That’s right: setUTCMonth is not even idempotent! Calling it a second time gives a different result than the first. What on Earth is going on? Two things, actually.
So what should you do to avoid this? I would recommend never using any setters on the Date class. It is fundamentally dangerous to change the year, month or date, because in all three cases you can get silent corruption of other fields. Treat Date objects as immutable, and make new ones when you need to. Use the “new Date(Date.UTC(…))” form I gave above.