Explain Codes LogoExplain Codes Logo

How to clone a Date object?

javascript
clone
date-object
timestamp
Alex KataevbyAlex Kataev·Oct 8, 2024
TLDR

To clone a JavaScript Date object, you can simply use:

const clonedDate = new Date(originalDate.getTime());

This method uses the getTime() function, which pulls the timestamp of originalDate. This timestamp is then used to create a new Date object, guaranteeing an exact, independent clone.

Deep-dive: Methods to clone a Date object

In your JavaScript journey, there will be times you need to duplicate your Date objects . Here, we will examine how to properly clone a Date object and insight on why it's crucial.

Copy cat using getTime() or valueOf()

You can use either the getTime method or the valueOf method to get the number of milliseconds since the epoch from your date - what a perfect timestamp for our clone!

// JavaScript's own Back to the Future machine, no DeLorean required! const cloneDate1 = new Date(originalDate.getTime()); const cloneDate2 = new Date(originalDate.valueOf());

Unary plus operator: not just for mathematicians

You can also just coerce your original Date to a number. Add on that unary plus and there you go - a perfectly cloned date!

// Look mum, no hands (or methods)! const cloneDate = new Date(+originalDate);

Tinker with your clones timestamps

Now that you've cloned your date, feel free to mess around with it! Any mutations you make will only affect the cloned date. So, go ahead, change the year, day, hour..., the original date won't be offended.

// Nothing like a little time traveling for your cloned date cloneDate.setFullYear(cloneDate.getFullYear() + 10);

The dangers of time travel: messing with the original

Cloning dates is needed to keep the original intact. Assigning a date to a new variable would cause any changes to also affect the original.

// The butterfly effect in action: changing “newDate” changes “originalDate” too! let newDate = originalDate; newDate.setFullYear(newDate.getFullYear() + 1000);

Tips, tricks, and trivia about Date Object Cloning

Time zones and you: a cloning story

Bear in mind that JavaScript's Date objects are made in the local time zone where the code executes. So when it comes to cloning, the time zone stays intact.

When cloning goes wrong: handling invalid dates

Trying to clone an invalid date just gives you another invalid date. Clone responsibly!

// Meet invalid's evil twin brother... invalid! const invalidDate = new Date('not a date'); const cloneInvalid = new Date(invalidDate.getTime());

The need for speed: performance with getTime()

If you're looking to clone a bunch of dates in a loop (or any other high pressure scenario), new Date(original.getTime()) is your new best friend.

The future is now: going native

While libraries like Moment.js added cool functions like clone(), JavaScript's evolving feature set makes it easier than ever to stick with native methods for cloning dates.