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

前端 未结 10 1254
轮回少年
轮回少年 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:21

    You can use the toJSON() method to get a DateTime style format

    var today = new Date().toJSON(); 
    // produces something like: 2012-10-29T21:54:07.609Z
    

    From there you can clean it up...

    To grab the date and time:

    var today = new Date().toJSON().substring(0,19).replace('T',' ');
    

    To grab the just the date:

    var today = new Date().toJSON().substring(0,10).replace('T',' ');
    

    To grab just the time:

    var today = new Date().toJSON().substring(10,19).replace('T',' ');
    

    Edit: As others have pointed out, this will only work for UTC. Look above for better answers.

提交回复
热议问题