如何在JavaScript中克隆Date对象
问题描述:
将Date变量分配给另一个变量会将引用复制到SAME值。这意味着改变一个将改变另一个。我如何实际克隆或复制该值?
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?
答
使用 Date 对象的 getTime()
方法,返回自1970年1月1日00:00:00(纪元时间):
var date = new Date();
var copiedDate = new Date(date.getTime());
在Safari 4中,您还可以写:
In Safari 4, you can also write:
var date = new Date();
var copiedDate = new Date(date);
...但我不确定这是否适用于其他浏览器。 (它似乎适用于IE8)。
...but I'm not sure whether this works in other browsers. (It seems to work in IE8).