How to Clone a Date Object in JavaScript
In this tutorial, we will show how you can clone or copy a Date instance. The following example clones the current date which becomes possible with the getTime() method of the Date object which returns the number of milliseconds since 1 January 1970 00:00:00 (epoch time):
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<script>
let currentDate;
currentDate = new Date();
document.write(currentDate);
let clonedDate = new Date(currentDate.getTime());
document.write("<br>" + clonedDate);
</script>
</body>
</html>
The valueOf() method for Date objects performs the same result as the getTime() method (the number of milliseconds since epoch time) and returns the primitive value of a Date object.
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<script>
let date = new Date()
document.write(date);
let copyOf = new Date(date.valueOf())
document.write("<br>" + copyOf);
</script>
</body>
</html>
The getTime() Method
The Date.prototype.getTime() method returns the number of milliseconds since the Unix Epoch. It uses UTC standard for the time representation. The method can be used to assign a date and time to another Date object. It is functionally equivalent to the valueOf() method.