How to clone a Date object?
JavascriptJavascript Problem Overview
Assigning a Date
variable to another one will copy the reference to the same instance. This means that changing one will change the other.
How can I actually clone or copy a Date
instance?
Javascript Solutions
Solution 1 - Javascript
Use the Date object's getTime()
method, which returns the number of milliseconds since 1 January 1970 00:00:00 UTC (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. (It seems to work in IE8).
Solution 2 - Javascript
This is the cleanest approach
let dat = new Date()
let copyOf = new Date(dat.valueOf())
console.log(dat);
console.log(copyOf);
Solution 3 - Javascript
var orig = new Date();
var copy = new Date(+orig);
console.log(orig, copy);
Solution 4 - Javascript
Update for 2021:
In one respect the notion of cloning a Date
object sounds grander than it really is. As far as I can tell, there’s only one piece of instance data, and that is the stored time. What we’re really doing is making a new object with the same time.
Whatever may have been the case in the past, the new Date()
constructor definitely accepts a Date
object as a single argument:
var date = new Date(); // with or without an argument
var date2 = new Date(date); // clone original date
The documentation at https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date, step 4(b) indicates that a Date
object is definitely acceptable, and that this is equivalent to new Date(date.valueOf())
, as suggested by some of the answers above. As I said, all you’re really doing is making a new Date
object with the same time as the other.
You’ll also find that the documentation at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date has been updated to include this.
Solution 5 - Javascript
Simplified version:
Date.prototype.clone = function () {
return new Date(this.getTime());
}
Solution 6 - Javascript
I found out that this simple assignmnent also works:
dateOriginal = new Date();
cloneDate = new Date(dateOriginal);
But I don't know how "safe" it is. Successfully tested in IE7 and Chrome 19.
Solution 7 - Javascript
function cloneMyDate(oldDate){
var newDate = new Date(this.oldDate);
}
I was passing oldDate to function and generating newDate from this.oldDate, but it was changing this.oldDate also.So i used the above solution and it worked.