robert robert - 2 months ago 4
Javascript Question

What is the best way to convert date from JavaScript string in format YYYYMMDD to JavaScript date?

What is best way to convert date from JavaScript 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);

Answer

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