Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 737
IVR Avenger Avatar asked Jun 18 '10 00:06

IVR Avenger


People also ask

What is toISOString in JavaScript?

toISOString() The toISOString() method returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long ( YYYY-MM-DDTHH:mm:ss. sssZ or ±YYYYYY-MM-DDTHH:mm:ss. sssZ , respectively).


2 Answers

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(); 
like image 109
o-o Avatar answered Oct 01 '22 04:10

o-o


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;
like image 28
Pierre Guilbert Avatar answered Oct 01 '22 05:10

Pierre Guilbert