November 4, 2023
In JavaScript, the 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 Date
object:
Using the new Date()
Constructor
const originalDate = new Date(); const copiedDate = new Date(originalDate);
In this case, originalDate
is copied to copiedDate
. Both will have the same date and time, but will be independent objects.
Using the Date.prototype.getTime()
Method
const originalDate = new Date(); const copiedDate = new Date(originalDate.getTime());
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:
const originalDate = new Date(); const dateArray = [originalDate.getTime()]; const copiedDate = new Date(...dateArray);
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.
Remember, Date
objects are mutable, so if you modify either originalDate
or copiedDate
(for example, by using setDate()
, 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:
javascriptCopy code function cloneDate(date) { return new Date(date.getTime()); } const originalDate = new Date(); const copiedDate = cloneDate(originalDate);
Ship faster, worry less with Basedash
How to Sort Object Array by Boolean Property in JavaScript
Max Musing
How to Truncate Date in MySQL
Max Musing
What is evented I/O for V8 JavaScript?
Max Musing
Replace + with Space in JavaScript
Max Musing
How to Sort JavaScript Objects by Key
Max Musing
How to Scroll Automatically to the Bottom of a Page in JavaScript
Max Musing