In JavaScript, the parse function is utilized to interpret the given date string, subsequently returning the quantity of milliseconds that have elapsed from the specified date to January 1, 1970. Should the input string contain invalid values or fail to be recognized, the function will yield NaN.
Measuring the milliseconds that elapse between two designated dates allows us to determine the quantity of hours, days, months, and more through straightforward calculations.
Syntax
date.parse(datestring);
This method takes a single string parameter that denotes a date. It returns a numeric value representing the total number of milliseconds.
Let’s examine a few examples of utilizing the parse method. In our initial example, we will provide a valid date value, while in the subsequent example, we will input an invalid date value to observe the outcome.
Example1
In this illustration, we are providing a valid date in order to calculate the total number of milliseconds that elapse from the given date to midnight on January 1, 1970.
Here, the specified date is "June 19, 2020" .
<html>
<head>
</head>
<body>
<h1> Hello World :) :) </h1>
<p> Here, we are finding the number of milliseconds between the given date and midnight of January 1, 1970. </p>
<script>
var d1 = "June 19, 2020";
var m1 = Date.parse(d1);
document.write("The number of milliseconds between <b> " + d1 + "</b> and <b> January 1, 1970 </b> is: <b> " + m1 + "</b>");
</script>
</body>
</html>
Output
Example2
In this illustration, we are supplying an incorrect date to observe the outcome when invalid input is given.
<html>
<head>
</head>
<body>
<h1> Hello World :) :) </h1>
<p> Here, we are finding the number of milliseconds between the given date and midnight of January 1, 1970. </p>
<script>
var d1 = "June 39, 2020"; //an invalid date
var m1 = Date.parse(d1);
document.write("The number of milliseconds between <b> " + d1 + "</b> and <b> January 1, 1970 </b> is: <b> " + m1 + "</b>");
</script>
</body>
</html>
Output
In the output, we can see the result is NaN .