В дополнение к ответу oo, я бы хотел порекомендовать отделить логические операции от возврата и вместо них поместить их в тройки в переменные.
Кроме того, используйте concat()
для обеспечения безопасной конкатенации переменных
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();
Чуть более сухая скрипка, как предложено RiZKiT
https://jsfiddle.net/EricHerlitz/tuhhfxz9/