November 4, 2023
Date object can be copied by creating a new
Date object and passing the value of the existing date to the constructor. Here are a few ways to copy a
new Date() Constructor
In this case,
originalDate is copied to
copiedDate. Both will have the same date and time, but will be independent objects.
getTime() returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. When you pass this value to the
Date constructor, it creates a new
Date object with the same time.
Using the Spread Operator in ES6
While the spread operator (
...) is commonly used to copy arrays and objects, it doesn't apply directly to date objects since they are not iterable. However, you can use the spread operator within an array or other iterable context:
This is not the most straightforward method for copying dates, but it demonstrates an indirect use of the spread operator with date values.
Using Object Destructuring (Not Recommended)
Like the spread operator, object destructuring is not directly applicable to date objects since they are not plain objects with enumerable properties that can be copied in this way.
Date objects are mutable, so if you modify either
copiedDate (for example, by using
setTime(), etc.), it will not affect the other date object since they are separate instances.
Clone a Date with a Function
If you find yourself needing to copy dates often, you might write a function to handle this for you:
How to Truncate Date in MySQL