JavaScript - Date object to YYYYMMDD

An easy way to turn a date object into a string in YYYYMMDD format, which is easier than concatenating Date.getYear(), Date.getMonth(), and Date.getDay().

Date.prototype.yyyymmdd = function() {
  var mm = this.getMonth() + 1; // getMonth() is zero-based
  var dd = this.getDate();
 
  return [this.getFullYear(), !mm[1] && '0', mm, !dd[1] && '0', dd].join(''); // padding
};
 
var date = new Date();
date.yyyymmdd();

or

To not modify native objects, and to use multiplication which some think is clearer than string padding use:

function yyyymmdd(dateIn) {
   var yyyy = dateIn.getFullYear();
   var mm = dateIn.getMonth()+1; // getMonth() is zero-based
   var dd  = dateIn.getDate();
   return String(10000*yyyy + 100*mm + dd); // Leading zeros for mm and dd
}
 
var today = new Date();
console.log(yyyymmdd(today));

or

Date.prototype.yyyymmdd = function() {
  var yyyy = this.getFullYear();
  var mm = this.getMonth() < 9 ? "0" + (this.getMonth() + 1) : (this.getMonth() + 1); // getMonth() is zero-based
  var dd  = this.getDate() < 10 ? "0" + this.getDate() : this.getDate();
  return "".concat(yyyy).concat(mm).concat(dd);
};
 
Date.prototype.yyyymmddhhmm = function() {
  var yyyy = this.getFullYear();
  var mm = this.getMonth() < 9 ? "0" + (this.getMonth() + 1) : (this.getMonth() + 1); // getMonth() is zero-based
  var dd  = this.getDate() < 10 ? "0" + this.getDate() : this.getDate();
  var hh = this.getHours() < 10 ? "0" + this.getHours() : this.getHours();
  var min = this.getMinutes() < 10 ? "0" + this.getMinutes() : this.getMinutes();
  return "".concat(yyyy).concat(mm).concat(dd).concat(hh).concat(min);
};
 
Date.prototype.yyyymmddhhmmss = function() {
  var yyyy = this.getFullYear();
  var mm = this.getMonth() < 9 ? "0" + (this.getMonth() + 1) : (this.getMonth() + 1); // getMonth() is zero-based
  var dd  = this.getDate() < 10 ? "0" + this.getDate() : this.getDate();
  var hh = this.getHours() < 10 ? "0" + this.getHours() : this.getHours();
  var min = this.getMinutes() < 10 ? "0" + this.getMinutes() : this.getMinutes();
  var ss = this.getSeconds() < 10 ? "0" + this.getSeconds() : this.getSeconds();
  return "".concat(yyyy).concat(mm).concat(dd).concat(hh).concat(min).concat(ss);
};
 
var d = new Date();
d.yyyymmdd();
d.yyyymmddhhmm();
d.yyyymmddhhmmss();

Using Date.toISOString()

WARNING: Date.toISOString() creates a UTC formatted date and hence can jump date boundaries depending on the timezone. E.g. in GMT+1: (new Date(2013,13, 25)).toISOString() == '2013-12-24T23:00:00.000Z'

To create a YYYY-MM-DD string of today's date:

var d = new Date().toISOString().slice(0,10);

or

var d = new Date();
var res = d.toISOString().slice(0,10).replace(/-/g,"");

To get YYYYMMDDHHmmSSsssuse this:

var ds = (new Date()).toISOString().replace(/[^0-9]/g, "");