如何克隆一个Date对象? [英] How to clone a Date object?

查看:46
本文介绍了如何克隆一个Date对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Date变量分配给另一个变量会将引用复制到同一实例.这意味着更改一个将更改另一个.

Assigning a Date variable to another one will copy the reference to the same instance. This means that changing one will change the other.

我该如何真正克隆或复制Date实例?

How can I actually clone or copy a Date instance?

推荐答案

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

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());

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

这篇关于如何克隆一个Date对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆