How can I convert string to datetime with format specification in JavaScript?

Serhat Ozgel picture Serhat Ozgel · Jan 24, 2009 · Viewed 598.4k times · Source

How can I convert a string to a date time object in javascript by specifying a format string?

I am looking for something like:

var dateTime = convertToDateTime("23.11.2009 12:34:56", "dd.MM.yyyy HH:mm:ss");

Answer

Christoph picture Christoph · Jan 24, 2009

Use new Date(dateString) if your string is compatible with Date.parse(). If your format is incompatible (I think it is), you have to parse the string yourself (should be easy with regular expressions) and create a new Date object with explicit values for year, month, date, hour, minute and second.