views:

33

answers:

1

What is best way to convert date from javscript string in format YYYYMMDD to javascript date format.

var from_date = document.getElementById('from_date').value;             
var YYYY = from_date.substring(0,4);
var MM = from_date.substring(4,7);
var DD = from_date.substring(7,8);      
+1  A: 

var myDate = new Date( parseInt(YYYY,10), parseInt(MM,10)-1, parseInt(DD,10) );

note that the month provided to the date constructor is actual month number - 1.

edits: ok, there are some issues with your date part extraction- substring is probably the most awkward of javascript's sub-stringing methods (sub,substr,substring). And after testing I stand by the month value having to be 1 less than the actual number. Here is a fixed sample.

var from_date = "20101127"; //document.getElementById('from_date').value; 
var YYYY = from_date.substring(0, 4);
var MM = from_date.substring(4, 6);
var DD = from_date.substring(6);
var myDate = new Date(parseInt(YYYY, 10), parseInt(MM, 10) - 1, parseInt(DD, 10)); 
alert(myDate); // should be november 27th 2010
lincolnk
I thought for sure you had to -1 the month as well, but in my testing that turned out to be untrue!
Josh Stodola
that's how it works in IE8 (all I have to test with at the moment). `alert( new Date(79,5,24) )` says June 24 1979.
lincolnk
Man, I don't know what the hell is wrong with Google Chrome but it was giving seriously inconsistent results.
Josh Stodola