我试图使用JS将日期对象转换为YYYYMMDD格式的字符串。有没有比连接Date.getYear(), Date.getMonth()和Date.getDay()更简单的方法?
当前回答
您可以简单地使用这一行代码来获取日期
var date = new Date().getFullYear() + "-" + (parseInt(new Date().getMonth()) + 1) + "-" + new Date().getDate();
其他回答
这段代码修复了Pierre Guilbert的答案:
(10000年后依然有效)
YYYYMMDD=new Date().toISOString().slice(0,new Date().toISOString().indexOf("T")).replace(/-/g,"")
对公认答案的一点变化:
函数getDate_yyyymmdd() { const date = new date (); const yyyy = date.getFullYear(); const mm = String(date.getMonth() + 1).padStart(2,'0'); const dd = String(date.getDate()).padStart(2,'0'); 返回“$ {yyyy} $ {mm} $ {dd} ' } console.log (getDate_yyyymmdd ())
除了o-o的答案之外,我还建议将逻辑操作与返回值分离,并将它们作为三元放入变量中。
另外,使用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 yyyymmdd = this.yyyymmdd(); var hh = this.getHours() < 10 ? "0" + this.getHours() : this.getHours(); var min = this.getMinutes() < 10 ? "0" + this.getMinutes() : this.getMinutes(); return "".concat(yyyymmdd).concat(hh).concat(min); }; Date.prototype.yyyymmddhhmmss = function() { var yyyymmddhhmm = this.yyyymmddhhmm(); var ss = this.getSeconds() < 10 ? "0" + this.getSeconds() : this.getSeconds(); return "".concat(yyyymmddhhmm).concat(ss); }; var d = new Date(); document.getElementById("a").innerHTML = d.yyyymmdd(); document.getElementById("b").innerHTML = d.yyyymmddhhmm(); document.getElementById("c").innerHTML = d.yyyymmddhhmmss(); <div> yyyymmdd: <span id="a"></span> </div> <div> yyyymmddhhmm: <span id="b"></span> </div> <div> yyyymmddhhmmss: <span id="c"></span> </div>
很好,很简单:
var date = new Date();
var yyyy = date.getFullYear();
var mm = date.getMonth() + 1; // getMonth() is zero-based
if (mm < 10) mm='0'+mm;
var dd = date.getDate();
if (dd < 10) dd='0'+dd;
/*date.yyyymmdd();*/
console.log('test - '+yyyy+'-'+mm+'-'+dd);
Try this:
函数showdate () {
var a = new Date();
var b = a.getFullYear();
var c = a.getMonth();
(++c < 10)? c = "0" + c : c;
var d = a.getDate();
(d < 10)? d = "0" + d : d;
var final = b + "-" + c + "-" + d;
return final;
}
document.getElementById("todays_date").innerHTML = showdate();