如何在 JavaScript 中克隆 Date 对象
要克隆 Date
对象:
-
使用
getTime()
方法获取自 Unix 纪元以来的毫秒数。 -
将结果传递给
Date()
构造函数。 -
例如,
const dateClone = new Date(date.getTime())
。
const date = new Date();
console.log(date);
const dateClone = new Date(date.getTime());
console.log(dateClone);
我们可以点击上面的 运行示例 查看实际运行结果。
getTime
方法返回一个数字,该数字表示 1970 年 1 月 1 日午夜和给定日期之间经过的毫秒数。
console.log(new Date().getTime());
Date()
构造函数可以传递一个时间戳作为参数,并创建一个新的 Date 对象来存储指定的日期和时间。
在使用任何改变 Date 对象的方法之前,克隆 Date 是最佳实践,例如 set*
。
const date = new Date('2022-09-24T09:25:00');
// 👇️ Sap Sep 24 2022 09:25:00
console.log(date);
const dateClone = new Date(date.getTime());
// 👇️ Sap Sep 24 2022 09:25:00
console.log(dateClone);
dateClone.setHours(0, 0, 0, 0);
// 👇️ Sat Sep 24 2022 00:00:00
console.log(dateClone);
// 👇️ Sat Sep 24 2022 09:25:00 (didn't change original)
console.log(date);
我们使用 getTime()
方法获取日期的时间戳并将其传递给 Date()
构造函数以获取 Date 对象。
当我们必须使用某些 set*
方法但又不想改变原始日期时,通常会使用此方法。
在示例中,我们使用 setHours()
方法更改克隆日期的小时、分钟、秒和毫秒。
setHours()
方法(以及所有其他set*
方法)更改给定日期的值,这并不总是我们想要的。
在使用该方法之前创建日期的克隆允许我们保留原始日期。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。