Get String in YYYYMMDD format from JS date object?

Get String in YYYYMMDD format from JS date object?

I’m trying to use JS to turn a date object into a string in YYYYMMDD format. Is there an easier way than concatenating Date.getYear(), Date.getMonth(), and Date.getDay()?

Solutions/Answers:

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:

If you don’t need a pure JS solution, you can use jQuery UI to do the job like this :

$.datepicker.formatDate('yymmdd', new Date());

I usually don’t like to import too much libraries. But jQuery UI is so useful, you will probably use it somewhere else in your project.

Visit http://api.jqueryui.com/datepicker/ for more examples

Solution 6:

This is a single line of code that you can use to create a YYYY-MM-DD string of today’s date.

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