Sometimes, we may need to clone a JavaScript date object in our code.
In this article, we’ll look at ways to clone a date object in our JavaScript code.
Date.prototype.getTime and the Date Constructor
We can pass a timestamp constructor to the Date
constructor.
So we can get the timestamp from the existing date object and then pass that into the Date
constructor.
For instance, we can write:
const date = new Date();
const copiedDate = new Date(date.getTime());
console.log(copiedDate)
We call getTime
to return the timestamp from the date
object.
Then we pass that to the Date
constructor to create the new date object.
And copiedDate
is a new date object.
Date.prototype.valueOf
We can also get the timestamp with the valueOf
method of a date object.
For instance, we can write:
const date = new Date();
const copiedDate = new Date(date.valueOf());
console.log(copiedDate)
And we get the same result as the previous example.
The Unary Plus Operator
Another way to get the timestamp from a JavaScript date object is to use the unary plus operator.
For instance, we can write:
const date = new Date();
const copiedDate = new Date(+date);
console.log(copiedDate)
And we get the same result as the previous examples.
Pass in the Date Object into the Date Constructor Directly
The Date
constructor also accepts a date object directly.
So we can use it to create a clone of our original date object.
For instance, we can write:
const date = new Date();
const copiedDate = new Date(date);
console.log(copiedDate)
And we get the same result as before.
Conclusion
There’re several ways we can use th clone a date object in JavaScript.
One way is to get the timestamp with various operators or methods and pass that into the Date
constructor.
The other way is to pass in the Date
instance itself to the Date
constructor to create a new Date
instance.