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.
The ES5 spec details the
new Date(value)form of theDateconstructor. In the algorithm for handling this form,valueis 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 callingdateArray.join().Therefore, your call to the
Dateconstructor will effectively look like this:If the string can be recognised by the
Date.parsemethod, you will end up with aDateinstance.This form of the
Dateconstructor is also listed on MDN asnew 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.