Is it possible to clone a Date in Javascript?

2

Is it possible to clone a Date() in Javascript ? That is, from a date variable, create another variable that has the same date.

In the following code you can see that when comparing fecha_1 and fecha_2 it gives false .

var fecha_1 = new Date()
var fecha_2 = new Date()
console.log("Son fechas "+(fecha_1==fecha_2?"iguales":"diferentes")+".")

I know you are comparing different objects and not being primitive so that gives false , but I would like to know if you can create a date with the same values as fecha_1 , that is, year, day, or even nanoseconds (milliseconds, or whatever). It must have exactly the data of the first date.

I would also like to know if there is any way to check if they are the same, in terms of time.

Note: If possible, it works in both Chrome and in Firefox , since I realized that they act differently when handling dates.

    
asked by ArtEze 20.03.2017 в 11:10
source

1 answer

7

You can clone Date objects in Javascript in the following way:

var original = new Date();
var copy = new Date(original);

Objects will always give you different things because, obviously, they are different objects. However, you can check that the value is exactly the same:

var original = new Date();
var copy = new Date(original);
console.log("Original: " + original + " - " + original.getTime());
console.log("Copy    : " + copy + " - " + copy.getTime())
console.log("Iguales: " + (original.getTime() == copy.getTime()))
    
answered by 20.03.2017 / 11:27
source