javascript – How to clone a Date object?

The Question :

553 people think this question is useful

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?

The Question Comments :

The Answer 1

818 people think this answer is useful

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).

The Answer 2

124 people think this answer is useful

This is the cleanest approach

let dat = new Date() 
let copyOf = new Date(dat.valueOf())

console.log(dat);
console.log(copyOf);

The Answer 3

27 people think this answer is useful

var orig = new Date();
var copy = new Date(+orig);

console.log(orig, copy);

The Answer 4

13 people think this answer is useful

Simplified version:

Date.prototype.clone = function () {
    return new Date(this.getTime());
}

The Answer 5

8 people think this answer is useful

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.

Add a Comment