Acceptable Notations of a Date String
ISO format examples include YYYY-MM-DD and YYYY-MM-DDTHH:MM:SS.
Method 1: Passing an ISO Date String directly Into the Date Constructor
To demonstrate this method, simply create a new date String with the following line:
dateString = «2005 FEB 25»;
After that, simply create a new variable and then set that variable equal to the Date constructor by using the keyword “new”, and in the constructor pass in the dateString as:
date1 = new Date(string);
Then simply pass this date1 variable to the console log function to display it on the terminal and also to verify that this is now a date variable constructed from a string:
Execute the code and observe the following output on the terminal:
It is clear from the result in the terminal that date1 is actually a date variable constructed from a string.
To demonstrate the use of an invalid date string, set the variable dateString equal to an invalid format like:
dateString = «2005 FEB 25th»;
Afterwards, do the same steps, pass this in the Date() constructor and show the result on the terminal using the console log function:
date1 = new Date(dateString);
Upon execution of this, the terminal shows the following outcome:
The result is as “Invalid Date”, which means that not every string can be interpreted into a date variable. That is why following the format for the date string is essential.
Method 2: Use the Date parse() Method to Parse the String First
In this second method, simply start by creating a new date string with the following line:
dateString2 = «1997 Jun 05»;
Now, simply pass this string inside the Date parse() to get the time elapsed from 1st January 1970, till the date represented in the string in the form of milliseconds:
milli = Date.parse(dateString2);
Afterwards, we can use these milliseconds to construct a new Date variable by passing them in the Date constructor like:
Afterwards, simply display the value of the date2 variable on the terminal by using the console log function:
Execute the program, and the terminal will display the following outcome:
It is clear from the output that this is a date variable constructed from the given string. However, if you notice the value on the output that the Date of the month part is one less than the value we passed in the String. It should be the 5th of June, but rather it is the 4th of June in the output.
The reason is that in the Date object or date variables, the “date of the month” part starts from 0 instead of 1. Therefore, the 5th of June 1997 is represented by “1997-06-04”.