views:

23191

answers:

5

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");
+1  A: 

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.

Christoph
+7  A: 

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

Theres a getDateFromFormat() function that you can tweak a little to solve your problem

Rafael Mueller
A: 

Date.parse() is fairly intelligent but I can't guarantee that format will parse correctly.

If it doesn't, you'd have to find something to bridge the two. Your example is pretty simple (being purely numbers) so a touch of REGEX (or even string.split() -- might be faster) paired with some parseInt() will allow you to quickly make a date.

Oli
+5  A: 

No sophisticated date/time formatting routines exist in JavaScript.

You will have to use an external library for formatted date output, "JavaScript Date Format" from Flagrant Badassery looks very promising.

For the input conversion, several suggestions have been made already. :)

Tomalak
"have to" is relative. Of course you can build your own implementation. :)
Tomalak
+1  A: 

var temp1=""; var temp2="";

        var str1 = fd; 
        var str2 = td; 
        var dt1  = str1.substring(0,2); 
        var mon1 = str1.substring(3,5); 
        var yr1  = str1.substring(6,10);  
        var dt2  = str2.substring(0,2); 
        var mon2 = str2.substring(3,5); 
        var yr2  = str2.substring(6,10); 
        temp1 = mon1 +"/"+ dt1 +"/"+ yr1;
        temp2 = mon2 +"/"+ dt2 +"/"+ yr2;


        var cfd = Date.parse(temp1);
        var ctd = Date.parse(temp2);


        var date1 = new Date(cfd); 
        var date2 = new Date(ctd);




       if(date1 > date2) 
                { 
                alert("FROM DATE SHOULD BE MORE THAN TO DATE");
                } 
navin