Passing An Array To The Javascript Date Constructor, Is It Standard?
Solution 1:
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 = newDate("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.
Solution 2:
You can use Spread Syntax in ES6.
let dateArray = [2012, 6, 5];
let dateObject = newDate(...dateArray);
console.log('Spread:', dateObject);
console.log('Direct:', newDate(2012, 6, 5));
Solution 3:
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.
Solution 4:
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.
functionnewInstance(clazz, arguments, scope) {
returnnew (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();
Post a Comment for "Passing An Array To The Javascript Date Constructor, Is It Standard?"