how to get formatted date time like 2009-05-29 21:55:57 using javascript?

前端 未结 10 1348
轮回少年
轮回少年 2021-02-01 14:33

when using new Date,I get something like follows:

Fri May 29 2009 22:39:02 GMT+0800 (China Standard Time)

but what I want is xxxx-xx-xx xx:xx:xx formatted time s

10条回答
  •  渐次进展
    2021-02-01 15:09

    jonathan's answers lacks the leading zero. There is a simple solution to this:

    function getFormattedDate(){
        var d = new Date();
    
        d = d.getFullYear() + "-" + ('0' + (d.getMonth() + 1)).slice(-2) + "-" + ('0' + d.getDate()).slice(-2) + " " + ('0' + d.getHours()).slice(-2) + ":" + ('0' + d.getMinutes()).slice(-2) + ":" + ('0' + d.getSeconds()).slice(-2);
    
        return d;
    }
    

    basically add 0 and then just take the 2 last characters. So 031 will take 31. 01 will take 01...

    jsfiddle

提交回复
热议问题