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

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

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


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.

Note: At the time of this edit, this is pretty popular: date-fns.org

UPDATE

There are now plenty of getters on the Date.prototype but just for the sake of fun code, here are some slick new moves:

const today = new Date().toJSON();
const [date, time] = today.split('T')
const [year, month, day] = date.split('-')
const [hour, minutes, secondsTZ] = time.split(':')
const [seconds, timezone] = secondsTZ.split('.')

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