Format JavaScript date as yyyy-mm-dd

后端 未结 30 2681
再見小時候
再見小時候 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:06

    Here is one way to do it:

    var date = Date.parse('Sun May 11,2014');
    
    function format(date) {
      date = new Date(date);
    
      var day = ('0' + date.getDate()).slice(-2);
      var month = ('0' + (date.getMonth() + 1)).slice(-2);
      var year = date.getFullYear();
    
      return year + '-' + month + '-' + day;
    }
    
    console.log(format(date));
    

提交回复
热议问题