JavaScript Date valueOf() Method
The JavaScript Date.valueOf() method returns a numeric value represents the number of milliseconds between the date object and Epoch. If the provided Date object is invalid, this method returns Not a Number (NaN) as result.
The Epoch is the starting point for measuring time in seconds and is defined as January 1, 1970, 00:00:00 UTC.
Syntax
Following is the syntax of JavaScript Date valueOf() Method −
valueOf();
This method does not accept any parameters.
Return Value
This method returns the number of milliseconds between the date object and midnight January 1, 1970 UTC.
Example 1
In the below example, we are demonstrating the basic usage of JavaScript Date valueOf() method −
<html> <body> <script> const currentDate = new Date(); const numericValue = currentDate.valueOf(); document.write(numericValue); </script> </body> </html>
Output
The program returns an integer that specifies the number of of milliseconds between the date object and epoch.
Example 2
Here, we are returning the number of milliseconds for a specific date (December 26, 2023 12:30:00) since the epoch −
<html>
<body>
<script>
const currentDate = new Date('December 26, 2023 12:30:00');
const specificDate = currentDate.valueOf();
document.write(specificDate);
</script>
</body>
</html>
Output
It returns "1703574000000" milliseconds as output.
Example 3
In the example below, the date object is created with an invalid date i.e. the date and time values that are outside the valid range.
<html>
<body>
<script>
const currentDate = new Date('December 45, 2023 21:78:001');
const specificDate = currentDate.valueOf();
document.write(specificDate);
</script>
</body>
</html>
Output
The program returns "invalid date" as a result.