node.js: weird setUTCMonth results

node.js: weird setUTCMonth results

Problem

Running this code in latest 0.8 and 0.10 versions of node:

> date = new Date(2013, 0, 1)
Tue Jan 01 2013 00:00:00 GMT+0200 (EET)
> date.setUTCMonth(5)
1341180000000
> date
Mon Jul 02 2012 01:00:00 GMT+0300 (EEST)

The year changed from 2013 to 2012 after .setUTCMonth was called. Why did that happen?

Problem courtesy of: Fluffy

Solution

The year changed from 2013 to 2012 after .setUTCMonth was called.

No, it did not.

Your local time zone is GMT+0200 – which means, your date that you see as Tue Jan 01 2013 00:00:00 GMT+0200 is really two hours earlier in GMT, so it’s December 31st 2012, 22:00:00.

And changing the month of that date to 5 makes your modified date end up being in July 2012 accordingly.

Solution courtesy of: CBroe

Discussion

Leave a Reply

Your email address will not be published. Required fields are marked *