In JavaScript, Date objects are mutable, so if you simply assign a Date object to a new variable, changes to the new variable will affect the original Date object. This article will walk you through a couple of different ways to create a truly new Date object that is a clone (or deep copy) of an existing Date object.
Using the Date() constructor
You can use the Date constructor to create a new Date object with the same value as the original Date object.
Example:
const originalDate = new Date('2023-03-07T12:30:00.000Z');
const clonedDate = new Date(originalDate);
// Modify clonedDate
clonedDate.setFullYear(2030);
clonedDate.setDate(8);
console.log("Original date:", originalDate);
console.log("Cloned date:", clonedDate);
Output:
Original date: 2023-03-07T12:30:00.000Z
Cloned date: 2030-03-08T12:30:00.000Z
Using the getTime() method
The getTime() method can help us create a new Date object with the same timestamp value as the original Date object.
Example:
const originalDate = new Date("2023-01-01T12:00:00.000Z");
// Get the timestamp
const timestamp = originalDate.getTime();
// Clone the date
const clonedDate = new Date(timestamp);
// Modify clonedDate
clonedDate.setFullYear(2024);
clonedDate.setMonth(11);
console.log("Original date:", originalDate);
console.log("Cloned date:", clonedDate);
Output:
Original date: 2023-01-01T12:00:00.000Z
Cloned date: 2024-12-01T12:00:00.000Z
What about using JSON.stringify() and JSON.parse()?
When you use JSON.stringify() on a Date object, it will convert the Date object into a string representation of the date. However, when you parse the string back into an object using JSON.parse(), it will not be a Date object but rather a string. Let me prove this fact with the code below:
const date = new Date("2029-01-01T00:00:00.000Z");
const json = JSON.stringify(date);
const clonedDate = JSON.parse(json);
console.log(clonedDate instanceof Date);
console.log(typeof clonedDate);
Output:
false
string
Given the above, it is better NOT to use JSON.stringify() to deep copy a Date object. If you still want to, you can do the following (it’s inefficient and too verbose):
// Original Date
const originalDate = new Date("2023-06-01T00:00:00.000Z");
// Clone Date
const clonedDate = new Date(JSON.parse(JSON.stringify(originalDate)));
// Modify the cloned date
clonedDate.setFullYear(2024);
// Log the original date
console.log("Original Date: ", originalDate);
// Log the cloned date
console.log("Cloned Date: ", clonedDate);
Output:
Original Date: 2023-06-01T00:00:00.000Z
Cloned Date: 2024-06-01T00:00:00.000Z
Conclusion
You’ve learned some techniques to deep copy a Date object in JavaScript. This knowledge can be helpful in some situations. For example, when implementing undo/redo functionality in an app, it may be necessary to clone Date objects in order to maintain the state of the application at different points in time.