Format JavaScript date as yyyy-mm-dd

后端 未结 30 3158
再見小時候
再見小時候 2020-11-22 01:28

I have a date with the format Sun May 11,2014. How can I convert it to 2014-05-11 using JavaScript?

30条回答
  •  孤城傲影
    2020-11-22 02:09

    Reformatting a date string is fairly straightforward, e.g.

    var s = 'Sun May 11,2014';
    
    function reformatDate(s) {
      function z(n){return ('0' + n).slice(-2)}
      var months = [,'jan','feb','mar','apr','may','jun',
                     'jul','aug','sep','oct','nov','dec'];
      var b = s.split(/\W+/);
      return b[3] + '-' +
        z(months.indexOf(b[1].substr(0,3).toLowerCase())) + '-' +
        z(b[2]);
    }
    
    console.log(reformatDate(s));

提交回复
热议问题