Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a Date in MM/dd/yyyy HH:mm:ss format in JavaScript? [duplicate]

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.

like image 338
Gendaful Avatar asked May 17 '12 08:05

Gendaful


People also ask

How convert dd mm yyyy string to date in JavaScript?

To convert dd/mm/yyyy string into a JavaScript Date object, we can pass the string straight into the Date constructor. const dateString = "10/23/2022"; const dateObject = new Date(dateString);

What is HH MM SS A?

HH:mm:ss - this format displays a 24-hour digital clock with leading zero for hours. It also displays minutes and seconds.

What is sssZ in date format?

Dates are formatted using the following format: "yyyy-MM-dd'T'hh:mm:ss'Z'" if in UTC or "yyyy-MM-dd'T'hh:mm:ss[+|-]hh:mm" otherwise. On the contrary to the time zone, by default the number of milliseconds is not displayed. However, when displayed, the format is: "yyyy-MM-dd'T'hh:mm:ss.


1 Answers

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

See also

like image 134
KooiInc Avatar answered Sep 29 '22 00:09

KooiInc