This tutorial will teach you how to change a string into a Date object.
How to Convert a Date object in JavaScript?
For converting a string to a Date object, use the following methods:
Let’s check them out one by one!
Method 1: Convert a String to a Date object Using Date.parse() Method
The “ Date.parse()” method is used to create a Date object from a string. The parse() method of the Date object parses a date string and gives the number of milliseconds as an output since midnight on January 1, 1970. It follows the “YYYY-MM-DD” format for the date.
Syntax
Follow the below-given syntax for the parse() method:
In the above syntax, “dateString” is the date added as a string.
Return Value
- It returns a value that is the sum of the milliseconds from January 1, 1970, 00:00:00 UTC, and the date derived by parsing the specified string used to represent a date.
- It returns NaN while passing an invalid date format as an argument.
Example
Create a variable “strToDate” and call the “Date.parse()” method by passing a string as a date:
Print the converted date stored in a variable using the “console.log()” method:
Output
The above output gives “NaN” because the string doesn’t match the Date format.
Now, pass the string in a proper format in a parse() method:
Output
The output shows a sum of the milliseconds from January 1, 1970, 00:00:00 UTC, and the date “2022-11-20”.
Method 2: Convert a String to a Date object Using Date() Constructor
The most frequently used method for creating a Date object from a string is the constructor of the Date object. To create a Date object from a string, pass the string to the Date() constructor as an argument in a proper format.
Syntax
The following syntax for the Date() constructor:
It takes the date in a string as a parameter.
Return Value
- It outputs a new Date object.
- It gives “Invalid Date” while passing an invalid date format as an argument.
Example
Invoke the Date() constructor by passing date in a string format as an argument and store the returned Date object in a variable “strToDate”:
Print the resultant Date object on the console using the “console.log()” method:
Output
The above output gives “Invalid Date” because the string doesn’t match the Date format.
Now, pass the date in a proper format in a Date constructor:
Output
The output displayed a new Date object.
Conclusion
For creating a Date object from a string, use the “Date()” constructor or the “parse()” method of the Date object. The parse() method parses a date as a string and gives a date in milliseconds from January 1, 1970, and the date is derived by parsing the specified string used to represent a date. The Date() constructor gives a new Date object and commonly utilized method for converting a string to a Date object. Both methods are thoroughly explained in this article with examples.