Home > Web Front-end > JS Tutorial > body text

How to Clone a Date Object in JavaScript?

DDD
Release: 2024-10-26 10:53:03
Original
763 people have browsed it

How to Clone a Date Object in JavaScript?

Cloning a Date Object

In JavaScript, assigning a Date object to another one merely copies the reference to the same instance. Consequently, any alterations made to one will be reflected in the other. This raises the question: how can we create a true clone or copy of a Date object?

This can be achieved using the Date object's getTime() method. This method retrieves the number of milliseconds elapsed since the epoch (1 January 1970 00:00:00 UTC).

To clone a Date object:

var date = new Date();
var copiedDate = new Date(date.getTime());
Copy after login

This method generates a new Date object initialized with the exact same time value as the original date.

Alternatively, in Safari 4, one can write:

var date = new Date();
var copiedDate = new Date(date);
Copy after login

However, the compatibility of this approach across different browsers remains uncertain.

The above is the detailed content of How to Clone 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!