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

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

    What you are looking for is toISOString that will be a part of ECMAScript Fifth Edition. In the meantime you could simply use the toJSON method found in json2.js from json.org.

    The portion of interest to you would be:

    Date.prototype.toJSON = function (key) {
      function f(n) {
        // Format integers to have at least two digits.
        return n < 10 ? '0' + n : n;
      }
      return this.getUTCFullYear()   + '-' +
           f(this.getUTCMonth() + 1) + '-' +
           f(this.getUTCDate())      + 'T' +
           f(this.getUTCHours())     + ':' +
           f(this.getUTCMinutes())   + ':' +
           f(this.getUTCSeconds())   + 'Z';
    };
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-02-01 15:19

    The Any+Time(TM) JavaScript Library's AnyTime.Converter object easily converts a JS Date object into ISO or virtually any other format... in fact, the format you want is the default format, so you could simply say:

    (new AnyTime.Converter()).format(new Date());
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题