Assigning a Date variable to another one will copy the reference to the SAME value. This means that changing one will change the other. How can I actually clone or copy the value?
+15
A:
Use the Date object's getTime()
method, which returns the number of milliseconds since 1 January 1970 00:00:00 (epoch time):
var date = new Date();
var copiedDate = new Date(date.getTime());
In Safari 4, you can also write:
var date = new Date();
var copiedDate = new Date(date);
...but I'm not sure whether this works in other browsers.
Steve Harrison
2009-07-07 07:24:00
Sometimes people also use JSON serialization and deserialization, but this one is better and much faster. +1 from me.
Robert Koritnik
2009-07-07 07:26:24
JSON for this snippet? Sounds like these people should get their basics clear... Like mistaking jQuery for JavaScript DOM.
Boldewyn
2009-07-07 07:57:23
Another way to write this nice solution would be to extend the Date prototype:`Date.prototype.clone = function() { return new Date(this.getTime()); };`Which you could then use as `copiedDate = date.clone();`
Ryan
2010-04-02 08:24:25
A:
BAD (original):
var myDate = new Date();
var myDate2 = new Date();
myDate2.setDate(myDate.getDate());
GOOD (new, edited):
var myDate = new Date();
var myDate2 = new Date(myDate.getTime());
crizCraig
2009-07-07 07:27:05
If "myDate" is in a different month or year to "myDate2", this won't work properly. Even if you go through and manually set the year, month, day, hours, seconds, minutes, and milliseconds, you'll run into problems caused by months not having the same number of days (especially February). Using the value of "getTime()" ensures that the cloned date is exactly the same as the original.
Steve Harrison
2009-07-07 07:38:49
@Steve - Ah right, I didn't realize setDate only set the day of the month. I'll change it lest anybody copies the worst answer ;)
crizCraig
2009-07-07 17:17:47
+2
A:
This is the cleanest approach
var dat = new Date()
var copyOf = new Date(dat.valueOf())
AnthonyWJones
2009-07-07 07:29:18
The "valueOf()" method for "Date" objects produces the same result as its "getTime()" method (the number of milliseconds since epoch time).
Steve Harrison
2009-07-07 07:32:18
@Steve: true, but getTime() could "looks" like it only returns the time and not include the date as well hence my reference to "cleanest". Frankly the Date type in Javascript is a bit of disaster zone, it should never have been mutable in the first place.
AnthonyWJones
2009-07-07 08:34:01