Home > Web Front-end > JS Tutorial > How to Create a True Copy of a Date Object in JavaScript?

How to Create a True Copy of a Date Object in JavaScript?

Patricia Arquette
Release: 2024-10-28 08:48:02
Original
251 people have browsed it

How to Create a True Copy of a Date Object in JavaScript?

Avoiding Date Object Mutability: Cloning Date Instances

When assigning a Date variable to another, the reference to the same instance is copied. Altering one instance affects the other. To create a true copy or clone of a Date instance, circumvent this behavior.

Solution:

Utilize the Date object's getTime() method, which retrieves the number of milliseconds elapsed since the epoch time (1 January 1970 00:00:00 UTC):

var date = new Date();  // Create the original Date object
var copiedDate = new Date(date.getTime());  // Clone the Date object
Copy after login

In Safari 4, an alternative approach is possible:

var date = new Date();  // Create the original Date object
var copiedDate = new Date(date);  // Clone the Date object
Copy after login

However, the compatibility of the latter approach across browsers is uncertain. It appears functional in IE8.

The above is the detailed content of How to Create a True Copy of a Date Object in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template