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!