Possible Duplicate:
Formatting a date in javascript
I know other possible formats in JavaScript Date object but I did not get on how to format the date to MM/dd/yyyy HH:mm:ss
format.
Please let me know if you come across such problem.
Try something like this
var d = new Date,
dformat = [d.getMonth()+1,
d.getDate(),
d.getFullYear()].join('/')+' '+
[d.getHours(),
d.getMinutes(),
d.getSeconds()].join(':');
If you want leading zero's for values < 10, use this number extension
Number.prototype.padLeft = function(base,chr){
var len = (String(base || 10).length - String(this).length)+1;
return len > 0? new Array(len).join(chr || '0')+this : this;
}
// usage
//=> 3..padLeft() => '03'
//=> 3..padLeft(100,'-') => '--3'
Applied to the previous code:
var d = new Date,
dformat = [(d.getMonth()+1).padLeft(),
d.getDate().padLeft(),
d.getFullYear()].join('/') +' ' +
[d.getHours().padLeft(),
d.getMinutes().padLeft(),
d.getSeconds().padLeft()].join(':');
//=> dformat => '05/17/2012 10:52:21'
See this code in jsfiddle
[edit 2019] Using ES20xx, you can use a template literal and the new padStart
string extension.
var dt = new Date();
console.log(`${
(dt.getMonth()+1).toString().padStart(2, '0')}/${
dt.getDate().toString().padStart(2, '0')}/${
dt.getFullYear().toString().padStart(4, '0')} ${
dt.getHours().toString().padStart(2, '0')}:${
dt.getMinutes().toString().padStart(2, '0')}:${
dt.getSeconds().toString().padStart(2, '0')}`
);