Passing an array to a 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 in the Android browser and 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 it will be July 5, 2012, as it should be, as well as what I get with Chrome.

My question is: the first sample part of the ECMA standard? Is Chrome really bleeding so much and I expect other browsers to support it in the future? Or is it just some kind of v8-ism that I should avoid for portability?

I am trying to find links for this particular form of the Date constructor, but could not get.

+8
javascript date
source share
4 answers

The ES5 specification describes the new Date(value) construct of the Date constructor. In the processing algorithm of this form, value 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 ) actually matches the call to dateArray.join() .

Therefore, your Date constructor call will look like this:

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

If the string can be recognized by the Date.parse method, you will get a Date instance.

This form of the Date constructor is also specified in MDN as new Date(dateString) .

Firefox seems to fail when you pass an array, but it succeeds if you pass a string representation of that array. I would say that Firefox is probably a bug, but I may misinterpret the ES5 specification.

+15
source share

How about this:

 new (Function.prototype.bind.apply( Date, [null].concat([2011, 11, 24]) )) 

You use apply to call the function you created with bind with the elements of the array as arguments.

Source: http://www.2ality.com/2011/08/spreading.html

+3
source share

You can use Distribution Syntax in ES6.

 let dateArray = [2012, 6, 5]; let dateObject = new Date(...dateArray); console.log('Spread:', dateObject); console.log('Direct:', new Date(2012, 6, 5)); 
+2
source share

Based on Jure answer . I clarified Sergio's question in the comments, indicating that null is essentially the scope of the call.

 function newInstance(clazz, arguments, scope) { return new (Function.prototype.bind.apply(clazz, [scope].concat(arguments))); } // Scope is not needed here. var date = newInstance(Date, [2003, 0, 2, 4, 5, 6]); // 1/2/2003, 4:05:06 AM (Locale = US EST) document.body.innerHTML = date.toLocaleString(); 
+1
source share

All Articles