[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
๐ŸŒ
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:
๐ŸŒ
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.
Discussions

How to format a Date in MM/dd/yyyy HH:mm:ss format in JavaScript? - Stack Overflow
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 l... More on stackoverflow.com
๐ŸŒ stackoverflow.com
format date (received in milliseconds) in yyyy-mm-dd hh-mm in jquery/javascript - Stack Overflow
I am getting date in milliseconds and I converted it into IST by : new Date(1487651547000) which outputs Tue Feb 21 2017 10:02:27 GMT+0530 (India Standard Time) Now, I need this date in below More on stackoverflow.com
๐ŸŒ stackoverflow.com
jquery - Convert date format yyyy-mm-dd hh-mm-ss to dd-mm-yyyy - Stack Overflow
I'm getting a date result from an API in the format yyyy-mm-dd (plus unwanted hh-mm-ss). I want to convert this to a dd-mm-yyyy format in jQuery, whats the easiest/quickest way? At the moment I'm ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Format JavaScript date as yyyy-mm-dd - Stack Overflow
I like the additional flexibility that this solution gives over the other answers to this question. I haven't thoroughly tested this, but for the format I desired (i.e. "yyyy-MM-dd hh:mm:ss"), it works just as expected. More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
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 - The function dateInYyyyMmDdHhMmSs takes a Date object as a parameter, divider โ€˜ โ€” โ€™ or โ€˜ / โ€™ and formats the date as YYYY-MM-DD hh:mm:ss.
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));

๐ŸŒ
GitHub
gist.github.com โ€บ Ivlyth โ€บ c4921735812dd2c0217a
format javascript date to format "YYYY-mm-dd HH:MM:SS" ยท GitHub
function NOW() { var date = new Date(); var aaaa = date.getUTCFullYear(); var gg = date.getUTCDate(); var mm = (date.getUTCMonth() + 1); if (gg < 10) gg = "0" + gg; if (mm < 10) mm = "0" + mm; var cur_day = aaaa + "-" + mm + "-" + gg; var hours = date.getUTCHours() var minutes = date.getUTCMinutes() var seconds = date.getUTCSeconds(); if (hours < 10) hours = "0" + hours; if (minutes < 10) minutes = "0" + minutes; if (seconds < 10) seconds = "0" + seconds; return cur_day + " " + hours + ":" + minutes + ":" + seconds; } console.log(NOW());
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);
Find elsewhere
๐ŸŒ
Dirask
dirask.com โ€บ posts โ€บ JavaScript-format-current-Date-to-yyyy-mm-dd-hh-mm-ss-SSS-13qwJp
JavaScript - format current Date to yyyy-mm-dd hh-mm-ss-SSS
// ONLINE-RUNNER:browser; function getDateInFormat_yyyy_mm_dd_hh_mm_ss_SSS() { function toString(number, padLength) { return number.toString().padStart(padLength, '0'); } let date = new Date(); let dateTimeNow = toString( date.getFullYear(), 4 ) + '_' + toString( date.getMonth() + 1, 2 ) + '_' + toString( date.getDate(), 2 ) + '__' + toString( date.getHours(), 2 ) + '_' + toString( date.getMinutes(), 2 ) + '_' + toString( date.getSeconds(), 2 ) + '_' + toString( date.getMilliseconds(), 3 ) ; return dateTimeNow; } console.log(getDateInFormat_yyyy_mm_dd_hh_mm_ss_SSS());
๐ŸŒ
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 ...
๐ŸŒ
Plunker
embed.plnkr.co โ€บ P05l1a โ€บ preview
Convert json date to date format in jQuery - Plunker
<!DOCTYPE html> <html> <head> <meta ... nowDate = new Date(parseInt(date.substr(6))); var result = ""; result += nowDate.format("ddd mmm dd yyyy HH:MM:ss") + " : ddd mmm dd yyyy HH:MM:ss <br/>"; result += nowDate.format("dd/mm/yyyy") + " : dd/mm/yyyy <br/>"; result += ...
๐ŸŒ
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?
In the example below, we have created the object of the date class and invoked the toISOString() method by taking the date object as a reference. It returns the string in the hh: mm: ss format. Also, it returns the ISO time, So users can't compare it with the local time.
๐ŸŒ
Day.js
day.js.org โ€บ docs โ€บ en โ€บ display โ€บ format
Format ยท Day.js
dayjs().format() // current date in ISO8601, without fraction seconds e.g. '2020-04-02T08:02:17-05:00' dayjs('2019-01-25').format('[YYYYescape] YYYY-MM-DDTHH:mm:ssZ[Z]') // 'YYYYescape 2019-01-25T00:00:00-02:00Z' dayjs('2019-01-25').format('DD/MM/YYYY') // '25/01/2019'
๐ŸŒ
Dotmaui
blog.dotmaui.com โ€บ 2017 โ€บ 10 โ€บ 17 โ€บ javascript-current-date-with-format-yyyy-mm-dd-hhmmss
Javascript โ€“ Current date with format yyyy-mm-dd hh:MM:ss โ€“ .Maui Blog
October 17, 2017 - function NOW() { var date = new Date(); var aaaa = date.getFullYear(); var gg = date.getDate(); var mm = (date.getMonth() + 1); if (gg < 10) gg = "0" + gg; if (mm < 10) mm = "0" + mm; var cur_day = aaaa + "-" + mm + "-" + gg; var hours = date.getHours() var minutes = date.getMinutes() var seconds = date.getSeconds(); if (hours < 10) hours = "0" + hours; if (minutes < 10) minutes = "0" + minutes; if (seconds < 10) seconds = "0" + seconds; return cur_day + " " + hours + ":" + minutes + ":" + seconds; } NOW(); // "2017-10-17 14:02:33"
๐ŸŒ
Jquery
forum.jquery.com โ€บ portal โ€บ en โ€บ community โ€บ topic โ€บ change-the-datetime-format-of-the-calender-control-to-mm-dd-yyy-hh-mm
Change the datetime format of the calender control to mm/dd/yyy hh:mm
February 20, 2018 - <%-- <asp:CompareValidator ID="CompareValidator1" ForeColor = "Red" runat="server" ControlToValidate = "tbStartTime" ControlToCompare = "tbEndTime" Display="Dynamic" Operator = "LessThan" Type = "Date" ErrorMessage="Start date must be less than End date."></asp:CompareValidator>--%>
๐ŸŒ
GitHub
gist.github.com โ€บ mohokh67 โ€บ e0c5035816f5a88d6133b085361ad15b
Get YYYY-MM-DD HH-MM-SS in JavaScript ยท GitHub
Get YYYY-MM-DD HH-MM-SS in JavaScript ยท Raw ยท timestamp-formatter.md ยท const formatedTimestamp = ()=> { const d = new Date() const date = d.toISOString().split('T')[0]; const time = d.toTimeString().split(' ')[0].replace(/:/g, '-'); return `${date} ${time}` } Sign up for free to join this conversation on GitHub.
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Global_Objects โ€บ Date
Date - JavaScript | MDN - Mozilla
DD is the day of the month, with two digits (01 to 31). Defaults to 01. T is a literal character, which indicates the beginning of the time part of the string. The T is required when specifying the time part. HH is the hour, with two digits (00 to 23). 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).