Borislav Hadzhiev
Mon Jan 24 2022·2 min read
Photo by Anthony Tran
To clone a date object:
getTime()
method to get the number of milliseconds since the Unix
Epoch.Date()
constructor.const dateClone = new Date(date.getTime())
.const date = new Date(); console.log(date); // 👉️ Mon Jan 24 2022 11:32:39 const dateClone = new Date(date.getTime()); console.log(dateClone); // 👉️ Mon Jan 24 2022 11:32:39
The getTime method returns a number that represents the milliseconds elapsed between midnight of the 1st of January 1970 and the given date.
// 👇️ 1643017048020 console.log(new Date().getTime());
The
Date()
constructor can be passed a timestamp as a parameter and creates a new Date
object storing the specified date and time.
It's a best practice to clone a date, before using any of the methods that
mutate the Date
object in place, e.g. set*
.
const date = new Date('2022-09-24T09:25:00'); // 👇️ Sap Sep 24 2022 09:25:00 console.log(date); const dateClone = new Date(date.getTime()); // 👇️ Sap Sep 24 2022 09:25:00 console.log(dateClone); dateClone.setHours(0, 0, 0, 0); // 👇️ Sat Sep 24 2022 00:00:00 console.log(dateClone); // 👇️ Sat Sep 24 2022 09:25:00 (didn't change original) console.log(date);
We used the getTime()
method to get a timestamp of the date and passed it to
the Date()
constructor to get a Date
object.
set*
methods, but don't want to mutate the original date.In the example, we used the setHours()
method to change the hour, minutes,
seconds and milliseconds of the cloned date.
setHours()
method (and all of the other set*
methods) changes the values for the given date in place, which is not always what you want.Creating a clone of the date before using the method allows us to preserve the original.