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

前端 未结 2 389
深忆病人
深忆病人 2021-01-16 12:13

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

var from_date = document.getElementById(\'from_date\').         


        
2条回答
  •  广开言路
    2021-01-16 12:39

    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
    

提交回复
热议问题