How can I convert a string to a Date object in JavaScript?
var st = "date in some format" var dt = new Date(); var dt_st = // st in Date format, same as dt.
Use the Date() constructor to convert a string to a Date object, e.g. const date = new Date('2022-09-24') . The Date() constructor takes a valid date string as a parameter and returns a Date object. Copied! We used the Date() constructor to convert a string to a Date object.
Using strptime() , date and time in string format can be converted to datetime type. The first parameter is the string and the second is the date time format specifier. One advantage of converting to date format is one can select the month or date or time individually.
To convert a dd/mm/yyyy string to a date:Pass the year, month minus 1 and the day to the Date() constructor. The Date() constructor creates and returns a new Date object.
The best string format for string parsing is the date ISO format together with the JavaScript Date object constructor.
Examples of ISO format: YYYY-MM-DD
or YYYY-MM-DDTHH:MM:SS
.
But wait! Just using the "ISO format" doesn't work reliably by itself. String are sometimes parsed as UTC and sometimes as localtime (based on browser vendor and version). The best practice should always be to store dates as UTC and make computations as UTC.
To parse a date as UTC, append a Z - e.g.: new Date('2011-04-11T10:20:30Z')
.
To display a date in UTC, use .toUTCString()
,
to display a date in user's local time, use .toString()
.
More info on MDN | Date and this answer.
For old Internet Explorer compatibility (IE versions less than 9 do not support ISO format in Date constructor), you should split datetime string representation to it's parts and then you can use constructor using datetime parts, e.g.: new Date('2011', '04' - 1, '11', '11', '51', '00')
. Note that the number of the month must be 1 less.
Alternate method - use an appropriate library:
You can also take advantage of the library Moment.js that allows parsing date with the specified time zone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With