Format JavaScript date as yyyy-mm-dd

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

    toISOString() assumes your date is local time and converts it to UTC. You will get an incorrect date string.

    The following method should return what you need.

    Date.prototype.yyyymmdd = function() {         
    
        var yyyy = this.getFullYear().toString();                                    
        var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based         
        var dd  = this.getDate().toString();             
    
        return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
    };
    

    Source: https://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/

提交回复
热议问题