How to Clone a Date object in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jan 24, 2022

banner

Photo from Unsplash

Clone a Date object in JavaScript #

To clone a date object:

  1. Use the getTime() method to get the number of milliseconds since the Unix Epoch.
  2. Pass the result to the Date() constructor.
  3. For example, const dateClone = new Date(date.getTime()).
index.js
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.

index.js
// 👇️ 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*.

index.js
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.

This approach is often used when you have to use some of the 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.

The 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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.