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()
?
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).
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();
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With