Let me start with a specific example of what I'm trying to do.
I have an array of year, month, day, hour, minute, second and millisecond components in the form [ 2008, 10, 8, 00, 16, 34, 254 ]
. I'd like to instantiate a Date object using the following standard constructor:
new Date(year, month, date [, hour, minute, second, millisecond ])
How can I pass my array to this constructor to get a new Date instance? [ Update: My question actually extends beyond this specific example. I'd like a general solution for built-in JavaScript classes like Date, Array, RegExp, etc. whose constructors are beyond my reach. ]
I'm trying to do something like the following:
var comps = [ 2008, 10, 8, 00, 16, 34, 254 ];
var d = Date.prototype.constructor.apply(this, comps);
I probably need a "new
" in there somewhere. The above just returns the current time as if I had called "(new Date()).toString()
". I also acknowledge that I may be completely in the wrong direction with the above :)
Note: No eval()
and no accessing the array items one by one, please. I'm pretty sure I should be able to use the array as is.
Update: Further Experiments
Since no one has been able to come up with a working answer yet, I've done more playing around. Here's a new discovery.
I can do this with my own class:
function Foo(a, b) {
this.a = a;
this.b = b;
this.toString = function () {
return this.a + this.b;
};
}
var foo = new Foo(1, 2);
Foo.prototype.constructor.apply(foo, [4, 8]);
document.write(foo); // Returns 12 -- yay!
But it doesn't work with the intrinsic Date class:
var d = new Date();
Date.prototype.constructor.call(d, 1000);
document.write(d); // Still returns current time :(
Neither does it work with Number:
var n = new Number(42);
Number.prototype.constructor.call(n, 666);
document.write(n); // Returns 42
Maybe this just isn't possible with intrinsic objects? I'm testing with Firefox BTW.
Date.fromArray = function (year, month, date, hours, minutes, seconds, ms) { return new Date(year, month, date, hours || 0, minutes || 0, seconds || 0, ms || 0); }
and then call it withDate.fromArray.apply(null,arraywithtime);
. Note that you must have at least the year, month and day or you will get an invalid date. – Grenville