Format JavaScript date as yyyy-mm-dd

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

    var d = new Date("Sun May 1,2014");
    
    var year  = d.getFullYear();
    var month = d.getMonth() + 1;
    var day   = d.getDate(); 
    
    month = checkZero(month);             
    day   = checkZero(day);
    
    var date = "";
    
    date += year;
    date += "-";
    date += month;
    date += "-";
    date += day;
    
    document.querySelector("#display").innerHTML = date;
        
    function checkZero(i) 
    {
        if (i < 10) 
        {
            i = "0" + i
        };  // add zero in front of numbers < 10
    
        return i;
    }

提交回复
热议问题