• JavaScript Video Tutorials

JavaScript Date.parse() Method



The Date.parse() method in JavaScript is a static method which is used to parse a string representation of a date and time and convert it into the number of milliseconds since January 1, 1970, 00:00:00 UTC (also known as the Unix Epoch). If the input string cannot be parsed, the method returns NaN (Not a Number).

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 parse() method −

date.parse(dateString);

The dateString will be the date string that we want to parse. It can be in different formats, such as "YYYY-MM-DD" or "YYYY-MM-DDTHH:mm:ss", and it can include time zone information.

Return Value

This method returns the number of milliseconds since January 1, 1970, 00:00:00 UTC (Unix Epoch) representing the date and time parsed from the input string.

Example 1

In the following example, we are passing the Date object to the JavaScript Date.parse() method −

<html>
<body>
<script>
   const currentDate = new Date();
   const timestamp = Date.parse(currentDate);

   document.write(timestamp);
</script>
</body>
</html>

Output

After executing, it returns time difference in milliseconds from epoch to the current date according to local time.

Example 2

In this example, we are calculating the difference in milliseconds from epoch to a specfic date "2023-12-27 12:30:00" −

<html>
<body>
<script>
   const dateString = '2023-12-27 12:30:00';
   const timestamp = Date.parse(dateString);

   document.write(timestamp);
</script>
</body>
</html>

Output

It returns "1703660400000" as output.

Example 3

Here, we are proving an invalid date to the Date.parse() method −

<html>
<body>
<script>
   const invalidDateString = 'This is not a date';
   const timestamp = Date.parse(invalidDateString);

   document.write(timestamp);
</script>
</body>
</html>

Output

It returns "NaN" as output.

Advertisements