Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clone a Date object?

Tags:

javascript

Assigning a Date variable to another one will copy the reference to the same instance. This means that changing one will change the other.

How can I actually clone or copy a Date instance?

like image 993
Árvíztűrő tükörfúrógép Avatar asked Jul 07 '09 07:07

Árvíztűrő tükörfúrógép


People also ask

Is JavaScript date immutable?

Any function you pass your Date to could potentially mutate your date without you knowing about it, which in turn could introduce nasty and hard-to-find bugs. The new Temporal API is immutable, meaning all methods return a new object instead of mutating the existing one.

Does the date class implement cloneable?

The clone() method of Date class in Java returns the duplicate of the passed Date object. This duplicate is just a shallow copy of the given Date object. Parameters: The method does not accept any parameters. Return Value: The method returns a clone of the object.


1 Answers

Use the Date object's getTime() method, which returns the number of milliseconds since 1 January 1970 00:00:00 UTC (epoch time):

var date = new Date(); var copiedDate = new Date(date.getTime()); 

In Safari 4, you can also write:

var date = new Date(); var copiedDate = new Date(date); 

...but I'm not sure whether this works in other browsers. (It seems to work in IE8).

like image 148
Steve Harrison Avatar answered Sep 22 '22 09:09

Steve Harrison