如何在JavaScript中克隆日期对象?

时间:2022-02-02 16:48:51

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?

将日期变量分配给另一个将把引用复制到相同的值。这意味着改变一个会改变另一个。如何克隆或复制该值?

6 个解决方案

#1


527  

Use the Date object's getTime() method, which returns the number of milliseconds since 1 January 1970 00:00:00 (epoch time):

使用日期对象的getTime()方法,该方法返回自1970年1月1日00:00:00:00(新纪元时间)以来的毫秒数:

var date = new Date();
var copiedDate = new Date(date.getTime());

In Safari 4, you can also write:

在Safari 4中,您还可以这样写:

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

…但我不确定这是否适用于其他浏览器。(它似乎在IE8中有效)。

#2


82  

This is the cleanest approach

这是最干净的方法

var dat = new Date() 

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

#3


14  

Simplified version:

简化版:

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

#4


10  

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

#5


7  

I found out that this simple assignmnent also works:

我发现这个简单的assignmnent也可以工作:

dateOriginal = new Date();
cloneDate = new Date(dateOriginal);

But I don't know how "safe" it is. Successfully tested in IE7 and Chrome 19.

但我不知道它有多“安全”。成功测试IE7和Chrome 19。

#6


1  

If you're going to add clone to Date prototype, then you might want to make it non-enumerable...

如果您打算将克隆添加到日期原型,那么您可能想让它成为不可枚举的……

Date.prototype = Object.defineProperty(Date.prototype, "clone", { 
        value: function (fromDate) { return new Date(fromDate.valueOf()); } 
    });

#1


527  

Use the Date object's getTime() method, which returns the number of milliseconds since 1 January 1970 00:00:00 (epoch time):

使用日期对象的getTime()方法,该方法返回自1970年1月1日00:00:00:00(新纪元时间)以来的毫秒数:

var date = new Date();
var copiedDate = new Date(date.getTime());

In Safari 4, you can also write:

在Safari 4中,您还可以这样写:

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

…但我不确定这是否适用于其他浏览器。(它似乎在IE8中有效)。

#2


82  

This is the cleanest approach

这是最干净的方法

var dat = new Date() 

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

#3


14  

Simplified version:

简化版:

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

#4


10  

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

#5


7  

I found out that this simple assignmnent also works:

我发现这个简单的assignmnent也可以工作:

dateOriginal = new Date();
cloneDate = new Date(dateOriginal);

But I don't know how "safe" it is. Successfully tested in IE7 and Chrome 19.

但我不知道它有多“安全”。成功测试IE7和Chrome 19。

#6


1  

If you're going to add clone to Date prototype, then you might want to make it non-enumerable...

如果您打算将克隆添加到日期原型,那么您可能想让它成为不可枚举的……

Date.prototype = Object.defineProperty(Date.prototype, "clone", { 
        value: function (fromDate) { return new Date(fromDate.valueOf()); } 
    });