Search code examples
javascriptdatedate-format

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


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.


Solution

  • [Addendum 12/2022]: Here's a library to format dates using Intl.DateTimeFormat.

    [Addendum 01/2024]: And here is a (ES-)Date manipulation library

    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][1]

    [edit 2019] Using ES20xx, you can use a template literal and the new padStart string extension.

    const dt = new Date();
    const padL = (nr, len = 2, chr = `0`) => `${nr}`.padStart(2, chr);
    
    console.log(`${
        padL(dt.getMonth()+1)}/${
        padL(dt.getDate())}/${
        dt.getFullYear()} ${
        padL(dt.getHours())}:${
        padL(dt.getMinutes())}:${
        padL(dt.getSeconds())}`
    );