Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k points)

I concatenate Date.getYear(), Date.getMonth(), and Date.getDay() to turn the date object into a String in YYYYMMDD format. Can anyone tell me is there an easier way to do this?

1 Answer

0 votes
by (19.7k points)

You can use the below code:

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();

Share

Interested in Java? Check out this Java tutorial by Intellipaat. 

Related questions

Browse Categories

...