Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"); 
like image 431
Serhat Ozgel Avatar asked Jan 24 '09 14:01

Serhat Ozgel


People also ask

How convert dd mm yyyy string to date in JavaScript?

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.

Which function is used convert string into date format?

Date() Function. as. Date() function in R Language is used to convert a string into date format.


2 Answers

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.

like image 129
Christoph Avatar answered Oct 07 '22 01:10

Christoph


I think this can help you: http://www.mattkruse.com/javascript/date/

There's a getDateFromFormat() function that you can tweak a little to solve your problem.

Update: there's an updated version of the samples available at javascripttoolbox.com

like image 33
Rafael Mueller Avatar answered Oct 06 '22 23:10

Rafael Mueller