Get String in YYYYMMDD format from JS date object?

Solution 1:

Altered piece of code I often use:

Date.prototype.yyyymmdd = function() {
  var mm = this.getMonth() + 1; // getMonth() is zero-based
  var dd = this.getDate();

  return [this.getFullYear(),
          (mm>9 ? '' : '0') + mm,
          (dd>9 ? '' : '0') + dd
         ].join('');
};

var date = new Date();
date.yyyymmdd();

Solution 2:

I didn't like adding to the prototype. An alternative would be:

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

<!-- Next line is for code snippet output only -->
document.body.innerHTML += res;

Solution 3:

You can use the toISOString function :

var today = new Date();
today.toISOString().substring(0, 10);

It will give you a "yyyy-mm-dd" format.

Solution 4:

Moment.js could be your friend

var date = new Date();
var formattedDate = moment(date).format('YYYYMMDD');

Solution 5:

new Date('Jun 5 2016').
  toLocaleString('en-us', {year: 'numeric', month: '2-digit', day: '2-digit'}).
  replace(/(\d+)\/(\d+)\/(\d+)/, '$3-$1-$2');

// => '2016-06-05'