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.