Syntax of date.parse()
The syntax of the date parse() method is rather simple; it is defined as
Note: Here, the String contains a date value inside it. Now, the user can give this representation in various formats.
The return value from the date parse() method is a numeric value that represents the amount of time elapsed in the form of milliseconds since January 1st, 1970. A NaN is returned as the outcome if the argument equals an invalid date.
Example 1: Passing a string in the parse() method
For this example, create a new string variable, and write a valid date inside that variable like
Then, pass this variable in the argument of the parse() method and set it equal to a new variable dateInMs:
Finally, print out the result stored inside the dateInMs variable onto the terminal using the console log function:
These lines are going to yield the following outcome when executed:
From the screenshot, observe that the output is a numeric value representing time in the form of milliseconds.
Example 2: Calculating the Years from the result of the parse() method
Create a new string with the following value inside it:
Pass it to the Date.parse() method and then print the result onto the console using the console log function:
Since, the result is going to be the amount of time elapsed since January 1st, 1970. We can calculate the years passed since 1970 using the following lines:
The equation (365*24*60*60*1000) is simply calculating the number of milliseconds inside a whole year. After that, divide the result of the parse() method by that number and then display it onto the console using the console log function:
The years passed since 1970 were printed onto the terminal.
Example: Passing Invalid Date to Date.parse() method
To demonstrate this, create a new string containing an invalid date as
The date represented by this string is the 31st of February, 2022, which is an invalid date. Pass this dateInString variable in the argument of the parse() method and pass the result to the console log function as
After executing this program, the following result would be displayed onto the terminal:
The result was NaN meaning depicting that the string contained an invalid date.
The Date.parse() method simply takes a string representing a specific date. Afterward, it returns the number of milliseconds elapsed since January 1970 according to the date in the string. In case there are wrong \ invalid dates in the string, the result would be a NaN value. Besides, whenever a new Date variable is created using the new Date() constructor, an indirect call is made to the Date.parse() method.