97

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.

Brett DeWoody
  • 59,771
  • 29
  • 135
  • 184
Gendaful
  • 5,522
  • 11
  • 57
  • 76

4 Answers4

166

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

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.

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

See also

KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • Thanks Kooilnc, I tried var d = new Date(); var dformat = [d.getMonth().join('/') + d.getDate().join('/')+ d.getFullYear()].join('/')+' ' +d.getHours().join(':')+d.getMinutes().join(':')+d.getSeconds()]; but i am getting "Uncaught SyntaxError: Unexpected token ] " . Do you know the reason? Thanks for the help – Gendaful May 17 '12 at 08:59
  • Your code is completely wrong (you can't use `d.getMonth().join('/')`). Try copying/running the code I gave in my answer *without changing it*. I have added a jsfiddle link for you – KooiInc May 17 '12 at 09:09
  • 1
    Your example is incorrect. He's asking for MM/dd and you've supplied the format dd/MM (european style). – Jeff Fischer Feb 06 '14 at 00:25
  • 2
    @JeffFischer Yep, that's why my answer stated "Try something *like* this". Anyway, adjusted the answer especially for you. – KooiInc Jul 17 '14 at 08:10
  • hi why did you used +1 after getMonth()? I tried removing it and it gave me incorrect month. Is some kind of conversion is happening? – Vishal Feb 06 '16 at 06:32
  • 1
    okay got it. It gives months from 0 to 11. – Vishal Feb 06 '16 at 06:45
  • above syntax helpful in my date formation – Narendra Maru Mar 02 '19 at 06:22
71

You can always format a date by extracting the parts and combine them using string functions in desired order:

var date = new Date();
var dateStr =
  ("00" + (date.getMonth() + 1)).slice(-2) + "/" +
  ("00" + date.getDate()).slice(-2) + "/" +
  date.getFullYear() + " " +
  ("00" + date.getHours()).slice(-2) + ":" +
  ("00" + date.getMinutes()).slice(-2) + ":" +
  ("00" + date.getSeconds()).slice(-2);
console.log(dateStr);
Salman A
  • 262,204
  • 82
  • 430
  • 521
  • 3
    Should be using getDate() for the date. Can't edit because SO want more than 6 chars edited... sigh. – Llyle Apr 28 '13 at 10:01
5
var d = new Date();

var curr_date = d.getDate();

var curr_month = d.getMonth();

var curr_year = d.getFullYear();

document.write(curr_date + "-" + curr_month + "-" + curr_year);

using this you can format date.

you can change the appearance in the way you want then

for more info you can visit here

Neji
  • 6,591
  • 5
  • 43
  • 66
-4

var d = new Date();

// calling the function
formatDate(d,4);


function formatDate(dateObj,format)
{
    var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ];
    var curr_date = dateObj.getDate();
    var curr_month = dateObj.getMonth();
    curr_month = curr_month + 1;
    var curr_year = dateObj.getFullYear();
    var curr_min = dateObj.getMinutes();
    var curr_hr= dateObj.getHours();
    var curr_sc= dateObj.getSeconds();
    if(curr_month.toString().length == 1)
    curr_month = '0' + curr_month;      
    if(curr_date.toString().length == 1)
    curr_date = '0' + curr_date;
    if(curr_hr.toString().length == 1)
    curr_hr = '0' + curr_hr;
    if(curr_min.toString().length == 1)
    curr_min = '0' + curr_min;

    if(format ==1)//dd-mm-yyyy
    {
        return curr_date + "-"+curr_month+ "-"+curr_year;       
    }
    else if(format ==2)//yyyy-mm-dd
    {
        return curr_year + "-"+curr_month+ "-"+curr_date;       
    }
    else if(format ==3)//dd/mm/yyyy
    {
        return curr_date + "/"+curr_month+ "/"+curr_year;       
    }
    else if(format ==4)// MM/dd/yyyy HH:mm:ss
    {
        return curr_month+"/"+curr_date +"/"+curr_year+ " "+curr_hr+":"+curr_min+":"+curr_sc;       
    }
}

Sunil Dodiya
  • 2,605
  • 2
  • 18
  • 21