JavaScript Date.parse() Method: Usage Examples

Here’s an example date parsing () method.

1518931800000 

The date.parse() method is used to know the exact number of milliseconds that have elapsed since midnight on January 1, 1970 to the date we provide.

The syntax is as follows:

Date.parse(datestring);

Parameters: This method accepts a single parameter as described above and below:

  • Date String: This parameter saves the date as a string.

Return Value: It returns an integer value representing the number of milliseconds between midnight on January 1, 1970 and the date provided. If the machine doesn’t recognize the string in any way or the input string is invalid, it will return “NaN” instead of an integer.

More code for the above method is as follows:

Procedure 1:

If the date string entered is incorrect, NaN is returned, i.e. not a number.

<script>
  
     // Taking wrong date string as input.
     var date = "February 48, 2018 12:30 PM" ;
      
     // calling parse function.
     var msec = Date.parse(date);
     document.write(msec);
      
</script>

The output is as follows:

NaN

Procedure 2: If the date string entered is incorrect, NaN is returned, i.e. it is not a number.

<script>
  
     // Taking wrong date string as input.
     var date = "June 22, 2012" ;
      
     // Calling parse function.
     var msec = Date.parse(date);
     document.write(msec);
      
</script>

The output is as follows:

1340303400000

Note: Once you get the number of milliseconds between two dates, you can easily find the number of hours, days, months, years, etc., with simple math.

Supported browsers: Supported browsers JavaScript Date parse() methods are listed below:

  • Google Chrome
  • Internet Explorer
  • Firefox
  • opera
  • Safari