Format JavaScript date as yyyy-mm-dd

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

    You can do:

    function formatDate(date) {
        var d = new Date(date),
            month = '' + (d.getMonth() + 1),
            day = '' + d.getDate(),
            year = d.getFullYear();
    
        if (month.length < 2) 
            month = '0' + month;
        if (day.length < 2) 
            day = '0' + day;
    
        return [year, month, day].join('-');
    }
    

    Usage example:

    alert(formatDate('Sun May 11,2014'));
    

    Output:

    2014-05-11
    

    Demo on JSFiddle: http://jsfiddle.net/abdulrauf6182012/2Frm3/

提交回复
热议问题