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

前端 未结 10 1372
轮回少年
轮回少年 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条回答
  •  Happy的楠姐
    2021-02-01 15:18

    Just another solution: I was trying to get same format( YYYY-MM-DD HH:MM:SS ) but date.getMonth() was found inaccurate. So I decided to derive the format myself.

    This code was deployed early 2015, and it works fine till date.

    var m_names =["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    
    var d = new Date();
    var spl = d.toString().split(' ');
    var mnth = parseInt(m_names.indexOf(spl[1])+1).toString();
    mnth = (mnth.length == 1) ? '0'+mnth : mnth
            //  yyyy   -   mm   -   dd       hh:mm:ss 
    var data = spl[3]+'-'+mnth+'-'+spl[2]+' '+spl[4]
    alert(data)
    

    Test the code in JSFIDDLE

提交回复
热议问题