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

Viewed 80047

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 string

11 Answers

Although it doesn't pad to two characters in some of the cases, it does what I expect you want

function getFormattedDate() {
    var date = new Date();
    var str = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " +  date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();

    return str;
}

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';
};

it may be overkill for what you want, but have you looked into datejs ?

Date.prototype.toUTCArray= function(){
    var D= this;
    return [D.getUTCFullYear(), D.getUTCMonth(), D.getUTCDate(), D.getUTCHours(),
    D.getUTCMinutes(), D.getUTCSeconds()];
}

Date.prototype.toISO= function(t){
    var tem, A= this.toUTCArray(), i= 0;
    A[1]+= 1;
    while(i++<7){
        tem= A[i];
        if(tem<10) A[i]= '0'+tem;
    }
    return A.splice(0, 3).join('-')+'T'+A.join(':');
    // you can use a space instead of 'T' here
}

Date.fromISO= function(s){
    var i= 0, A= s.split(/\D+/);
    while(i++<7){
        if(!A[i]) A[i]= 0;
        else A[i]= parseInt(A[i], 10);
    }
    --s[1];
    return new Date(Date.UTC(A[0], A[1], A[2], A[3], A[4], A[5]));  
}

   var D= new Date();
   var s1= D.toISO();
   var s2= Date.fromISO(s1);
   alert('ISO= '+s1+'\nlocal Date returned:\n'+s2);

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());

Modernised version of @Toskan's answer:

const getFormattedDate = (d = new Date()) => 
   d.getFullYear() + "-" +
   (d.getMonth() + 1).toString().padStart(2, '0') + "-" +
   d.getDate().toString().padStart(2, '0') + " " +
   d.getHours().toString().padStart(2, '0') + ":" +
   d.getMinutes().toString().padStart(2, '0') + ":" +
   d.getSeconds().toString().padStart(2, '0');

console.log(getFormattedDate());   //  2022-07-28 12:44:44
Related