- Date() constructor
The first and simplest way to convert a string to a date object is to use and call the Date() along with using a string in an argument. For example, const date = new Date(str). When you pass a string, the constructor Date() makes a date object, which is stored in the new date. The getFullYear in the console log shows the year and getDate displays date.
If you use it this way, it works. Passing a string with an unsupported or incorrect format throws an error or you just get an invalid date as an output. This is the only thing you need to avoid, which I learned after getting stuck with invalid output.
- Using non-ISO-8601 format
To have a parsing behavior to be consistent on all browsers, the string defined in the Date() constructor in the ISO 8601 format; YYYY-MM-DDTHH:mm:ss.sssZ. To convert a string with a non-ISO-8601 along with retaining a constant parsing behavior, you need to obtain date component values individually from a string, which is then passed to Date() as numbers.
You can convert a string to a date object. It shows the date, and if you want to have time in hours, minutes, and seconds, set the str to the date and time. Store it in str.split(), and then calling the variable in the console log displays date as well as time. The same way you get the month, date, and year as well as hour minutes, and seconds.
When I was struggling to get the same result, I tried this, and it works. If you want to convert a string to both date and time, then it is a must-try.
- Using date-fns parse()
The parse() is a function that is used from the NPM package’s date-fns to convert many strings in different formats to a date object. You can specify the string format as MM-DD-YYYY hh:m:ss to correctly convert. Similar to the above method, you need to set date and time to parse the str to convert a string to the date. After parsing, when you call the log, you get the hour using the getHour(), date using the getDate().
It is as effective as the above ways. I have tried this method, and to my surprise, it works fine. You need to use it correctly to avoid issue, and get the desired output.