在本教程中,我们将展示如何克隆或者复制 Date 实例。
以下示例使用 Date 对象的 getTime() 方法克隆当前日期,该方法返回自 1970 年 1 月 1 日 00:00:00(纪元时间)以来的毫秒数:
<!DOCTYPE html> <html> <head> <title>文档的标题</title> </head> <body> <script> let currentDate; currentDate = new Date(); console.log(currentDate); let clonedDate = new Date(currentDate.getTime()); console.log("<br>" + clonedDate); </script> </body> </html>
Date 对象的 valueOf() 方法执行与 getTime() 方法相同的结果(自纪元以来的毫秒数)并返回 Date 对象的原始值。
<!DOCTYPE html> <html> <head> <title>文档的标题</title> </head> <body> <script> let date = new Date() console.log(date); let copyOf = new Date(date.valueOf()) console.log("<br>" + copyOf); </script> </body> </html>
getTime() 方法
Date.prototype.getTime() 方法返回自 Unix Epoch 以来的毫秒数。
它使用 UTC 标准来表示时间。
该方法可用于将日期和时间分配给另一个 Date 对象。
它在功能上等同于 valueOf() 方法。
日期:2020-06-02 22:16:11 来源:oir作者:oir