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
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
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!