我试图使用JS将日期对象转换为YYYYMMDD格式的字符串。有没有比连接Date.getYear(), Date.getMonth()和Date.getDay()更简单的方法?
当前回答
从ES6开始,你可以使用模板字符串使它更短:
var now = new Date();
var todayString = `${now.getFullYear()}-${now.getMonth()}-${now.getDate()}`;
这个解决方案没有零垫。看看其他好的答案,看看如何做到这一点。
其他回答
下面是一种更通用的方法,它允许日期和时间组件,并且可以作为数字或字符串进行相同的排序。
根据“Date ISO format”中的数字顺序,转换为本地时区,去掉非数字。例如:
// monkey patch version
Date.prototype.IsoNum = function (n) {
var tzoffset = this.getTimezoneOffset() * 60000; //offset in milliseconds
var localISOTime = (new Date(this - tzoffset)).toISOString().slice(0,-1);
return localISOTime.replace(/[-T:\.Z]/g, '').substring(0,n || 20); // YYYYMMDD
}
使用
var d = new Date();
// Tue Jul 28 2015 15:02:53 GMT+0200 (W. Europe Daylight Time)
console.log(d.IsoNum(8)); // "20150728"
console.log(d.IsoNum(12)); // "201507281502"
console.log(d.IsoNum()); // "20150728150253272"
如果你不介意包含一个额外的(但很小的)库,Sugar.js为在JavaScript中处理日期提供了很多不错的功能。 格式化日期,使用format函数:
new Date().format("{yyyy}{MM}{dd}")
这个帖子中最受欢迎的答案的简化版本https://stackoverflow.com/a/3067896/5437379:
function toYYYYMMDD(d) {
var yyyy = d.getFullYear().toString();
var mm = (d.getMonth() + 101).toString().slice(-2);
var dd = (d.getDate() + 100).toString().slice(-2);
return yyyy + mm + dd;
}
对公认答案的一点变化:
函数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 ())
您可以简单地使用这一行代码来获取日期
var date = new Date().getFullYear() + "-" + (parseInt(new Date().getMonth()) + 1) + "-" + new Date().getDate();