Wednesday, June 8, 2011

Beware of the JavaScript Date() Object, Its Evil!

Ok, it's not evil at all. It's actually a really useful object.

But today I came across a weird issue (although it may be an issue for me, maybe its just the intended core JavaScript design). Either way, this has not been documented well and could cause a lot of issues.

As you know you create a new Date object like this:
new Date();

This returns the datetime of now, which looks like this:
Date {Wed Jun 08 2011 16:42:28 GMT+1000 (AUS Eastern Standard Time)}

The Issue:
According to the W3Schools documentation here (JavaScript Date Object) you can also create a Date object like using this format - "new Date(year, month, day, hours, minutes, seconds, milliseconds)".

However, if you do something like this:
new Date(79,11,24,11,33,0);

You get this result:
Date {Mon Dec 24 1979 11:33:00 GMT+1100 (AUS Eastern Daylight Time)}

Notice that I sent in "11" as the month but the Date object shows "Dec".

As the months are always ahead by one, the most obvious reason why this is happening is because the value "11" I sent in is used as a index in a array to look up the Month value. This would explain why I have to use 0 to get the "Jan" month.

I wish this was documented better someplace.

The Real Potential Headache
Ok, now lets say we didn't realize this issue and created our dates using the params above, and we try to do date calculations on different Date objects.

E.g: we want to work out the time difference between two dates like so

var dateInPast = new Date(2011,6,7,00,00,0); 
// Thu Jul 07 2011 00:00:00

var dateNow = new Date(); 
// Wed Jun 08 2011 17:03:32

// note, getTime() gives num of ms since Jan 1, 1970
var dT = dateNow.getTime() - dateInPast.getTime();

dT gives you this answer -2444187757 (which is in milliseconds), the fact that its in minus is completely wrong as the dateInPast should clearly be less than dateNow

Pay extra attention when working with Date objects
I use the Date Object a lot and have never come across this until today, which makes you wonder what other quirks this object has.

Update 9/6/2011:
This seems to be documented in the Mozilla Developer Network docs found here.
"Integer value representing the month, beginning with 0 for January to 11 for December."

No comments:

Post a Comment

Fork me on GitHub