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

Answer from KooiInc on Stack Overflow
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Date
Date - JavaScript | MDN
As a special case, 24:00:00 is allowed, and is interpreted as midnight at the beginning of the next day. Defaults to 00. mm is the minute, with two digits (00 to 59). Defaults to 00. ss is the second, with two digits (00 to 59). Defaults to 00. sss is the millisecond, with three digits (000 to 999).
Top answer
1 of 4
181

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

2 of 4
73

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

function formatDate(date) {
  let datePart = [
    date.getMonth() + 1,
    date.getDate(),
    date.getFullYear()
  ].map((n, i) => n.toString().padStart(i === 2 ? 4 : 2, "0")).join("/");
  let timePart = [
    date.getHours(),
    date.getMinutes(),
    date.getSeconds()
  ].map((n, i) => n.toString().padStart(2, "0")).join(":");
  return datePart + " " + timePart;
}

let date = new Date();
console.log("%o => %s", date, formatDate(date));

🌐
W3Schools
w3schools.com › js › js_date_formats.asp
JavaScript Date Formats
ISO dates can be written with added hours, minutes, and seconds (YYYY-MM-DDTHH:MM:SSZ): const d = new Date("2015-03-25T12:00:00Z"); Try it Yourself » · Date and time is separated with a capital T. UTC time is defined with a capital letter Z. If you want to modify the time relative to UTC, remove the Z and add +HH:MM or -HH:MM instead:
🌐
Byby
byby.dev › js-format-date
How to parse and format a date in JavaScript
- ISO 8601: YYYY-MM-DDTHH:mm:ss.sssZ (e.g. 2022-05-30T00:00:00.000Z) - Short date: mm/dd/yyyy or dd/mm/yyyy (e.g. 04/24/2023 or 24/04/2023) - Long date: MMMM dd, yyyy (e.g. April 24, 2023) - RFC 2822: EEE, dd MMM yyyy HH:mm:ss GMT (e.g. Mon, 24 Apr 2023 00:00:00 GMT) - Unix timestamp: the number ...
🌐
Medium
trymysolution.medium.com › javascript-date-as-in-yyyy-mm-dd-hh-mm-ss-format-or-mm-dd-yyyy-hh-mm-ss-a0c96e8fa888
JavaScript Date as in YYYY-MM-DD hh:mm:ss Format or MM/DD/YYYY hh:mm:ss | by Yogesh D V | Medium
April 11, 2023 - function padTwoDigits(num: number) ... string = "-") { // :::: Exmple Usage :::: // The function takes a Date object as a parameter and formats the date as YYYY-MM-DD hh:mm:ss....
Top answer
1 of 3
9

Short and Sweetttt....

var myDate = new Date(1559736267189);
alert(myDate.getFullYear() + '-' +('0' + (myDate.getMonth()+1)).slice(-2)+ '-' +  ('0' + myDate.getDate()).slice(-2) + ' '+myDate.getHours()+ ':'+('0' + (myDate.getMinutes())).slice(-2)+ ':'+myDate.getSeconds());
        

2 of 3
1

Use below function in fiddle

     <a href="https://jsfiddle.net/pareshmutha1900/mbcmf0k4/">Link</a>

     var dateFormat = function () {
            var    token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
                timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
                timezoneClip = /[^-+\dA-Z]/g,
                pad = function (val, len) {
                    val = String(val);
                    len = len || 2;
                    while (val.length < len) val = "0" + val;
                    return val;
                };

            // Regexes and supporting functions are cached through closure
            return function (date, mask, utc) {
                var dF = dateFormat;

                // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
                if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
                    mask = date;
                    date = undefined;
                }

                // Passing date through Date applies Date.parse, if necessary
                date = date ? new Date(date) : new Date;
                if (isNaN(date)) throw SyntaxError("invalid date");

                mask = String(dF.masks[mask] || mask || dF.masks["default"]);

                // Allow setting the utc argument via the mask
                if (mask.slice(0, 4) == "UTC:") {
                    mask = mask.slice(4);
                    utc = true;
                }

                var    _ = utc ? "getUTC" : "get",
                    d = date[_ + "Date"](),
                    D = date[_ + "Day"](),
                    m = date[_ + "Month"](),
                    y = date[_ + "FullYear"](),
                    H = date[_ + "Hours"](),
                    M = date[_ + "Minutes"](),
                    s = date[_ + "Seconds"](),
                    L = date[_ + "Milliseconds"](),
                    o = utc ? 0 : date.getTimezoneOffset(),
                    flags = {
                        d:    d,
                        dd:   pad(d),
                        ddd:  dF.i18n.dayNames[D],
                        dddd: dF.i18n.dayNames[D + 7],
                        m:    m + 1,
                        mm:   pad(m + 1),
                        mmm:  dF.i18n.monthNames[m],
                        mmmm: dF.i18n.monthNames[m + 12],
                        yy:   String(y).slice(2),
                        yyyy: y,
                        h:    H % 12 || 12,
                        hh:   pad(H % 12 || 12),
                        H:    H,
                        HH:   pad(H),
                        M:    M,
                        MM:   pad(M),
                        s:    s,
                        ss:   pad(s),
                        l:    pad(L, 3),
                        L:    pad(L > 99 ? Math.round(L / 10) : L),
                        t:    H < 12 ? "a"  : "p",
                        tt:   H < 12 ? "am" : "pm",
                        T:    H < 12 ? "A"  : "P",
                        TT:   H < 12 ? "AM" : "PM",
                        Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
                        o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
                        S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
                    };

                return mask.replace(token, function ($0) {
                    return $0 in flags ? flags[0.slice(1, $0.length - 1);
                });
            };
        }();

        // Some common format strings
        dateFormat.masks = {
            "default":      "ddd mmm dd yyyy HH:MM:ss",
            shortDate:      "m/d/yy",
            mediumDate:     "mmm d, yyyy",
            longDate:       "mmmm d, yyyy",
            fullDate:       "dddd, mmmm d, yyyy",
            shortTime:      "h:MM TT",
            mediumTime:     "h:MM:ss TT",
            longTime:       "h:MM:ss TT Z",
            isoDate:        "yyyy-mm-dd",
            isoTime:        "HH:MM:ss",
            isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
            isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
        };

        // Internationalization strings
        dateFormat.i18n = {
            dayNames: [
                "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
                "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
            ],
            monthNames: [
                "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
                "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
            ]
        };

        // For convenience...
        Date.prototype.format = function (mask, utc) {
            return dateFormat(this, mask, utc);
        };





    today = new Date();
    var dateString = today.format("yyyy-mm-dd h:mm");
    alert(dateString);
🌐
Moment.js
momentjs.com › docs
Moment.js | Docs
For example, .12 is always 120 milliseconds, passing SS will not cause it to be interpreted as 12 milliseconds. Z ZZ were added in version 1.2.0. S SS SSS were added in version 1.6.0. X was added in version 2.0.0. SSSSS ... SSSSSSSSS were added in version 2.10.5. ... Unless you specify a time zone offset, parsing a string will create a date in the current time zone. moment("2010-10-20 4:30", "YYYY-MM-DD HH:mm"); // parsed as 4:30 local time moment("2010-10-20 4:30 +0000", "YYYY-MM-DD HH:mm Z"); // parsed as 4:30 UTC
Find elsewhere
🌐
JavaScript.info
javascript.info › tutorial › the javascript language › data types
Date and time
YYYY-MM-DD – is the date: year-month-day. The character "T" is used as the delimiter. HH:mm:ss.sss – is the time: hours, minutes, seconds and milliseconds.
🌐
Bobby Hadz
bobbyhadz.com › blog › javascript-format-date-yyyy-mm-dd-hh-mm-ss
Format a Date as YYYY-MM-DD hh:mm:ss in JavaScript | bobbyhadz
We used the addition (+) operator to add a space in the middle of the strings to get the date and time formatted as YYYY-MM-DD hh:mm:ss.
🌐
TutorialsPoint
tutorialspoint.com › how-to-convert-a-date-object-to-string-with-format-hh-mm-ss-in-javascript
How to convert a date object to string with format hh:mm:ss in JavaScript?
The Moment.JS library for the date ... requirements. Users can follow the syntax below to use the moment().format() method. let date = moment(); let dateStr = date.format("YY-MM-DD HH:mm:ss");...
🌐
GeeksforGeeks
geeksforgeeks.org › node.js › how-to-format-the-current-date-in-mm-dd-yyyy-hhmmss-format-using-node-js
How to format the current date in MM/DD/YYYY HH:MM:SS format using Node? - GeeksforGeeks
July 23, 2025 - This code utilizes the `moment` library to format the current date and time. The first `console.log` prints the date and time in the MM/DD/YYYY HH:mm:ss format (24-hour clock), while the second one uses the hh:mm:ss format (12-hour clock).
🌐
regex101
regex101.com › library › z4KHFC
regex101: Date and Time (yyyy-MM-dd HH:mm:ss)
Date Validation with leap year handling, & it takes care of date validation in the format like :mm/dd/yyyy or mmddyyyy or mm-dd-yyyy or m/d/yyyy or m-d-yyyy. 12/01/1986 02/29/2016 02/29/2015 13/31/1986 12/31/1980 1/32/2015 1/31/2015 01012016 01/01/2016 1/1/2016 1/1/16 01/01/16 01-01-2016 1-1-2016 1-1-16 01-01-16 Submitted by Ashish ... Checks if a expiry date is: mm/yy. You still have to check if it is a valid expiry date timewise.Submitted by Pevawi ... This is a regular expression for date in javascript.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-format-datetime-to-yyyy-mm-dd-hhmmss-in-momentjs
How to Format Datetime to YYYY-MM-DD HH:MM:SS in Moment.js? - GeeksforGeeks
July 23, 2025 - In this approach, we are using toISOString to convert the Moment.js object to a standardized ISO string. We then extract the relevant portion of the ISO string (up to the first 19 characters) and replace the 'T' separator with a space to format it as 'YYYY-MM-DD HH:mm:ss'.
🌐
MSR
rajamsr.com › home › javascript date format yyyy-mm-dd: easy way to format
Javascript Date Format YYYY-MM-DD: Easy Way to Format | MSR - Web Dev Simplified
March 3, 2024 - The slice() method extracts the date and time portion of the string yyyy-mm-dd hh:mm:ss and replaces the ‘T’ separator with an empty space.