Home  >  Article  >  Web Front-end  >  How to Clone a Date Object in JavaScript?

How to Clone a Date Object in JavaScript?

DDD
DDDOriginal
2024-10-26 10:53:03764browse

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

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

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!

Statement:
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