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

前端 未结 4 827
轻奢々
轻奢々 2020-12-18 22:21

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 Androi

相关标签:
4条回答
  • 2020-12-18 22:44

    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.

    0 讨论(0)
  • 2020-12-18 22:55

    You can use Spread 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));

    0 讨论(0)
  • 2020-12-18 22:56

    How about this:

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

    You use apply to call the new function you created using bind with array items as arguments.

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

    0 讨论(0)
  • 2020-12-18 22:58

    Based on Jure's answer. I have cleared up Sergio's question in the comments by showing that the null is, in fact, 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();

    0 讨论(0)
提交回复
热议问题