我试图使用JS将日期对象转换为YYYYMMDD格式的字符串。有没有比连接Date.getYear(), Date.getMonth()和Date.getDay()更简单的方法?
当前回答
从ES6开始,你可以使用模板字符串使它更短:
var now = new Date();
var todayString = `${now.getFullYear()}-${now.getMonth()}-${now.getDate()}`;
这个解决方案没有零垫。看看其他好的答案,看看如何做到这一点。
其他回答
Moment.js可以成为你的朋友
var date = new Date();
var formattedDate = moment(date).format('YYYYMMDD');
有些日期=新日期(); =某物。 游戏机。log (dateFormated);
js有很多有用的日期解析方法。
require (" datejs)
(新的日期()).toString(“名称”)
使用padStart:
Date.prototype.yyyymmdd = function() {
return [
this.getFullYear(),
(this.getMonth()+1).toString().padStart(2, '0'), // getMonth() is zero-based
this.getDate().toString().padStart(2, '0')
].join('-');
};
一个衬线(2022),带正确的时区偏移
var dateDisplay = new Date(Date.now() - (new Date().getTimezoneOffset() * 1000 * 60)).toJSON().slice(0, 10).replaceAll("-", "");
// YearMonthDay var dateDisplay = new Date(Date.now() - (new Date().getTimezoneOffset() * 1000 * 60)).toJSON().slice(0, 10).replaceAll("-", ""); console.log("YearMonthDay"); console.log(dateDisplay); // Year-Month-Day var dateDisplay = new Date(Date.now() - (new Date().getTimezoneOffset() * 1000 * 60)).toJSON().slice(0, 10); console.log("Year-Month-Day"); console.log(dateDisplay); // Year-Month-Day Hour:Minute:Second var dateDisplay = new Date(Date.now() - (new Date().getTimezoneOffset() * 1000 * 60)).toJSON().slice(0, 19).replace("T", " "); console.log("Year-Month-Day Hour:Minute:Second"); console.log(dateDisplay); // Year-Month-Day Hour-Minute-Second var dateDisplay = new Date(Date.now() - (new Date().getTimezoneOffset() * 1000 * 60)).toJSON().slice(0, 19).replace("T", " ").replaceAll(":", "-"); console.log("Year-Month-Day Hour-Minute-Second"); console.log(dateDisplay); // ISO-8601 standard: YYYY-MM-DDTHH:mm:ss.sssZ var dateDisplay = new Date(Date.now() - (new Date().getTimezoneOffset() * 1000 * 60)).toJSON(); console.log("ISO-8601 standard: YYYY-MM-DDTHH:mm:ss.sssZ"); console.log(dateDisplay);