javascript:date_object_to_yyyymmdd
This is an old revision of the document!
JavaScript - Date object to YYYYMMDD
An easy way to turn a date object into a string in YYYYMMDD format, which is easier than concatenating Date.getYear(), Date.getMonth(), and Date.getDay().
Date.prototype.yyyymmdd = function() { var mm = this.getMonth() + 1; // getMonth() is zero-based var dd = this.getDate(); return [this.getFullYear(), !mm[1] && '0', mm, !dd[1] && '0', dd].join(''); // padding }; var date = new Date(); date.yyyymmdd();
or
To not modify native objects, and to use multiplication which some think is clearer than string padding use:
function yyyymmdd(dateIn) { var yyyy = dateIn.getFullYear(); var mm = dateIn.getMonth()+1; // getMonth() is zero-based var dd = dateIn.getDate(); return String(10000*yyyy + 100*mm + dd); // Leading zeros for mm and dd } var today = new Date(); console.log(yyyymmdd(today));
or
Date.prototype.yyyymmdd = function() { var yyyy = this.getFullYear(); var mm = this.getMonth() < 9 ? "0" + (this.getMonth() + 1) : (this.getMonth() + 1); // getMonth() is zero-based var dd = this.getDate() < 10 ? "0" + this.getDate() : this.getDate(); return "".concat(yyyy).concat(mm).concat(dd); }; Date.prototype.yyyymmddhhmm = function() { var yyyy = this.getFullYear(); var mm = this.getMonth() < 9 ? "0" + (this.getMonth() + 1) : (this.getMonth() + 1); // getMonth() is zero-based var dd = this.getDate() < 10 ? "0" + this.getDate() : this.getDate(); var hh = this.getHours() < 10 ? "0" + this.getHours() : this.getHours(); var min = this.getMinutes() < 10 ? "0" + this.getMinutes() : this.getMinutes(); return "".concat(yyyy).concat(mm).concat(dd).concat(hh).concat(min); }; Date.prototype.yyyymmddhhmmss = function() { var yyyy = this.getFullYear(); var mm = this.getMonth() < 9 ? "0" + (this.getMonth() + 1) : (this.getMonth() + 1); // getMonth() is zero-based var dd = this.getDate() < 10 ? "0" + this.getDate() : this.getDate(); var hh = this.getHours() < 10 ? "0" + this.getHours() : this.getHours(); var min = this.getMinutes() < 10 ? "0" + this.getMinutes() : this.getMinutes(); var ss = this.getSeconds() < 10 ? "0" + this.getSeconds() : this.getSeconds(); return "".concat(yyyy).concat(mm).concat(dd).concat(hh).concat(min).concat(ss); }; var d = new Date(); d.yyyymmdd(); d.yyyymmddhhmm(); d.yyyymmddhhmmss();
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);
or
An alternative would be:
var d = new Date(); var res = d.toISOString().slice(0,10).replace(/-/g,"");
I wanted YYYYMMDDHHmmSSsss, so I did this:
var ds = (new Date()).toISOString().replace(/[^0-9]/g, "");
javascript/date_object_to_yyyymmdd.1467919520.txt.gz · Last modified: 2020/07/15 09:30 (external edit)