Edward Samson Edward Samson - 17 days ago 6
Javascript Question

Passing an array to the Javascript Date constructor, is it standard?

This works in Chrome:

var dateArray = [2012, 6, 5];
var dateObject = new Date(dateArray);


And I get June 5, 2012. I also tried on an Android browser and I get the same results. However, the same does not work in Firefox or Safari. I could say:

var dateObject = new Date(2012, 6, 5);


But that would be July 5, 2012, as it should, and is also what I get with Chrome.

My question: is the first example part of the ECMA standard? Is it just that Chrome is more bleeding edge and could I expect other browsers to support it in the future? Or is it just some v8-ism that I should avoid for portability?

I've been trying to find references for this specific form of the Date constructor but could not get any.

Answer

The ES5 spec details the new Date(value) form of the Date constructor. In the algorithm for handling this form, value is converted to a primitive value by calling the [[DefaultValue]] internal method of the object.

Converting an array to a primitive value is basically done by converting the array to a string. Converting an array to a string (Array.prototype.toString) is effectively the same as calling dateArray.join().

Therefore, your call to the Date constructor will effectively look like this:

var dateObject = new Date("2012,6,5");

If the string can be recognised by the Date.parse method, you will end up with a Date instance.

This form of the Date constructor is also listed on MDN as new Date(dateString).

Firefox seems to fail when you pass an array, but it succeeds if you pass the string representation of that array. I would say that that's probably a Firefox bug, but I may be misinterpreting the ES5 spec.