0

According to MDN, we can pass only the following types of parameters to Date constructor:

new Date(); new Date(value); // Unix timestamp new Date(dateString); new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]); 

So technically, we can't pass another Date instance to the Date constructor.

However, the following works fine in Firefox and Chrome:

new Date(new Date(1990, 1, 1)); 

Why does it work? Is this a correct way to clone Date objects?

1 Answer 1

1

According to the ECMAScript specification, 9th edition (from June 2018)

If Type(value) is Object and value has a [[DateValue]] internal slot, then Let tv be thisTimeValue(value).

So the behavior you observe is a standard (not some experimentation), and should be implemented by all modern browsers.

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you! Are you aware of any info on the actual progress of implementing this one across browsers (maybe caniuse.com or something)?
Until ECMAScript 2015 (ed 6), implementations were required to convert the date to a string using their implementation dependent toString, then parse that (why? no idea). The result was that IE did not correctly parse its own dates outside of the 20th century (IE's date string used 2 digit years and parsed them all to 19xx), so a safe way to copy a date was new Date(+date) to use the time value instead. Y2K issues lingered long after 2000. ;-)
@AlexanderAbakumov I don't know where you can find this information, except on every browser editor's website
Thank you! And the last question, please. Is it indeed the new recommended way to clone dates now for browsers supporting new Date(date);? So, can we now stop doing new Date(date.getTime()).
Well this is now in the standard to get rid of the previous techniques, each one hackier than the last (plus sign to convert to number, etc...) so the only reason why you wouldn't use it is for backwards compatibility

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.