How to Clone a Date Object in JavaScript
Read the tutorial and learn two useful methods that are used to clone the Date object in JavaScript. Get the current date and the cloned one right away.
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 <kbd class="highlighted">getTime()</kbd> method of the Date object which returns the number of milliseconds since 1 January 1970 00:00:00 (epoch time):
Javascript clone a date object
<!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 <kbd class="highlighted"> valueOf()</kbd> method for Date objects performs the same result as the <kbd class="highlighted">getTime()</kbd> method (the number of milliseconds since epoch time) and returns the primitive value of a Date object.
Javascript clone 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 <kbd class="highlighted">Date.prototype.getTime()</kbd> 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 <kbd class="highlighted"> valueOf()</kbd> method.