How to convert American date format to European

前端 未结 3 511
无人及你
无人及你 2020-12-11 19:26

from : 5/19/2011

to : 2011-05-19

I need it to raise an error when it finds that it cannot be real like 5/40/2011 etc.

3条回答
  •  情歌与酒
    2020-12-11 20:26

    Keep it simple:

    [edit] right, you wanted a check too, so added fn chkDat:

    function zeroPad(n){
      return (parseInt(n,10)<10 ? '0' : '') + n;
    }
    
    var usdat = '5/19/2011'.split('/')
        ,eudat = [usdat[2],zeroPad(usdat[0]),zeroPad(usdat[1])];
    
    alert(chkDat(usdat,eudat); //=> true
    alert(eudat.join('-'));    //=> '2011-05-19'
    
    function chkDat(orig,eu){
       var eu = new Date(eu.join('/'));
       return   eu.getMonth()+1 === parseInt(orig[0],10)
             && eu.getDate() === parseInt(orig[1],10)
             && eu.getFullYear() === parseInt(orig[2],10)
       ;
    }
    

    Note the date format you're after is called Calendar date (ISO 8601).

提交回复
热议问题