var date = new Date();

alert( date.getFullYear() + ("0" + (date.getMonth() + 1)).slice(-2) + ("0" + date.getDate()).slice(-2) + ("0" + date.getHours() ).slice(-2) + ("0" + date.getMinutes()).slice(-2) + ("0" + date.getSeconds()).slice(-2) );

edit

function pad2(n) { return n < 10 ? '0' + n : n }

var date = new Date();
    
alert( date.getFullYear().toString() + pad2(date.getMonth() + 1) + pad2( date.getDate()) + pad2( date.getHours() ) + pad2( date.getMinutes() ) + pad2( date.getSeconds() ) );
Answer from gurvinder372 on Stack Overflow
🌐
GitHub
gist.github.com › Ivlyth › c4921735812dd2c0217a
format javascript date to format "YYYY-mm-dd HH:MM:SS" · GitHub
var f_s_ymd_hms = function(n_unix_ts_ms){ var o_date = new Date(n_unix_ts_ms); var s_hms_ymd = `${o_date.getFullYear().toString().padStart(2,'0')}-${(o_date.getMonth()+1).toString().padStart(2,'0')}-${o_date.getDate().toString().padStart(2,'0')} ${o_date.getHours().toString().padStart(2,'0')}:${o_date.getMinutes().toString().padStart(2,'0')}:${o_date.getSeconds().toString().padStart(2,'0')}` }
🌐
W3Schools
w3schools.com › js › js_date_formats.asp
JavaScript Date Formats
Independent of input format, JavaScript will (by default) output dates in full text string format: ISO 8601 is the international standard for the representation of dates and times. The ISO 8601 syntax (YYYY-MM-DD) is also the preferred JavaScript date format: const d = new Date("2015-03-25"); Try it Yourself » · The computed date will be relative to your time zone.
🌐
W3docs
w3docs.com › javascript
How to Format a JavaScript Date
It operates with both Node.js and JavaScript, which is great as you do not have to learn several date/time libraries for front-end and back-end programming. moment().format('YYYY-MM-DD HH:m:s'); // now() -> 2020-03-20 14:32:20 moment("20161031", ...
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Date
Date - JavaScript | MDN
There are many ways to format a date as a string. The JavaScript specification only specifies one format to be universally supported: the date time string format, a simplification of the ISO 8601 calendar date extended format.
🌐
Mastering JS
masteringjs.io › tutorials › fundamentals › date-tostring-format-yyyy-mm-dd
Format a JavaScript Date to YYYY MM DD - Mastering JS
const month = (date.getMonth() + 1) * 100; // months are numbered 0-11 in JavaScript, * 100 to move two digits to the left. 20210011 => 20211100 const day = date.getDate(); // 20211100 => 20211124 const result = year + month + day + '' // `+ ''` to convert to string from number, 20211124 => "20211124" // in one line date.getFullYear() * 1e4 + (date.getMonth() + 1) * 100 + date.getDate() + ''; // "20211124"
🌐
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) ... object as a parameter, divider ‘ — ’ or ‘ / ’ and formats the date as YYYY-MM-DD hh:mm:ss....
🌐
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
Join the date-related strings with a hyphen and the time-related ones with a colon. ... Copied!function padTo2Digits(num) { return num.toString().padStart(2, '0'); } function formatDate(date) { return ( [ date.getFullYear(), padTo2Digits(date.getMonth() + 1), padTo2Digits(date.getDate()), ].join('-') + ' ' + [ padTo2Digits(date.getHours()), padTo2Digits(date.getMinutes()), padTo2Digits(date.getSeconds()), ].join(':') ); } // 👇️ 2023-01-04 10:00:07 console.log(formatDate(new Date())); // 👇️️ 2025-05-04 05:24:07 console.log(formatDate(new Date('May 04, 2025 05:24:07')));
Find elsewhere
🌐
Bobby Hadz
bobbyhadz.com › blog › javascript-format-date-yyyymmdd
Format a Date as YYYY-MM-DD using JavaScript | bobbyhadz
The method takes a locale and an options object and customizes the string according to the supplied values. When the year is set to numeric, it gets formatted to 4 digits. We formatted the month and day to 2 digits by using the 2-digit value. The last step is to place the date components in an array and join them with a hyphen separator.
🌐
JSFiddle
jsfiddle.net › felipekm › MYpQ9
YYYYMMDDHHMMSS Date Format - JSFiddle - Code Playground
For now it's a BYOK implmentation which means you need to provide your own API Key − you can get it for free.
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 › mohokh67 › e0c5035816f5a88d6133b085361ad15b
Get YYYY-MM-DD HH-MM-SS in JavaScript · GitHub
Save mohokh67/e0c5035816f5a88d6133b085361ad15b to your computer and use it in GitHub Desktop. Download ZIP · 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.
🌐
Zuga
zuga.net › articles › javascript-date-the-tostring-methods
Zuga.net | Javascript - Date() - the toString() methods
The Javascript Date type · doesn't support custom format strings like "yyyyMMddHHmmss". But it does provide a number of methods that return the date as a string in a specific format.
🌐
Chris Pietschmann
pietschsoft.com › post › 2023 › 09 › 28 › javascript-format-date-to-string
JavaScript: Format Date to String | Chris Pietschmann
September 28, 2023 - Create a Date object: First, create a JavaScript Date object representing the date you want to format. Define a formatting function: Create a function that takes the Date object and formats it according to your desired format. You can do this manually or use a library like date-fns or moment.js for more advanced formatting options. Use the formatting function: Call the formatting function with your Date object as the argument to get the formatted date string.
Top answer
1 of 2
7

The code looks good and works well. Since it provides a useful bit of work, you should convert it into a function. Then you can copy that function to another program if you need so.

function yyyymmdd() {
    var x = new Date();
    var y = x.getFullYear().toString();
    var m = (x.getMonth() + 1).toString();
    var d = x.getDate().toString();
    (d.length == 1) && (d = '0' + d);
    (m.length == 1) && (m = '0' + m);
    var yyyymmdd = y + m + d;
    return yyyymmdd;
}

To make this code a little easier to read, you should rename x to now.

You could also omit the calls to toString(), which makes the code a little shorter. Plus, you should introduce the variables mm and dd, so that you don't reassign to the d and m variables. This is a generally useful pattern, because when stepping through the code you can always look at the variable definition to see how it was computed. This is not possible for variables that change their value during execution.

The modified code looks like this:

function yyyymmdd() {
    var now = new Date();
    var y = now.getFullYear();
    var m = now.getMonth() + 1;
    var d = now.getDate();
    var mm = m < 10 ? '0' + m : m;
    var dd = d < 10 ? '0' + d : d;
    return '' + y + mm + dd;
}

Or, you could inline the last few lines:

function yyyymmdd() {
    var now = new Date();
    var y = now.getFullYear();
    var m = now.getMonth() + 1;
    var d = now.getDate();
    return '' + y + (m < 10 ? '0' : '') + m + (d < 10 ? '0' : '') + d;
}

That last variant is harder to read though, therefore I prefer the previous one.

Another possibility is to define a helper function that produces a two-digit string:

function yyyymmdd() {
    function twoDigit(n) { return (n < 10 ? '0' : '') + n; }

    var now = new Date();
    return '' + now.getFullYear() + twoDigit(now.getMonth() + 1) + twoDigit(now.getDate());
}
2 of 2
3

For getting the 0 padded date and month values, I generally follow this approach:

let d = ('0' + x.getDate()).substring(-2)

However, the Date objects have a .toISOString method, which returns the string in YYYY-MM-DDTHH:MM:SSZ format, which you can split on T and then replace - (or vice-versa):

formatted_date = (new Date()).toISOString().replace(/-/g, '').split('T')[0]
  // same as     (new Date()).toISOString().split('T')[0].replace(/-/g, '')
🌐
W3Schools
w3schools.com › jsref › jsref_toisostring.asp
JavaScript Date toISOString() Method
The toISOString() method returns a date object as a string, using the ISO standard. The standard is called ISO-8601 and the format is: YYYY-MM-DDTHH:mm:ss.sssZ · toISOString() is an ECMAScript5 (ES5 2009) feature.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Date › parse
Date.parse() - JavaScript | MDN
// Standard date-time string format const unixTimeZero = Date.parse("1970-01-01T00:00:00Z"); // Non-standard format resembling toUTCString() const javaScriptRelease = Date.parse("04 Dec 1995 00:12:00 GMT"); console.log(unixTimeZero); // Expected output: 0 console.log(javaScriptRelease); // Expected output: 818035920000