我试图使用JS将日期对象转换为YYYYMMDD格式的字符串。有没有比连接Date.getYear(), Date.getMonth()和Date.getDay()更简单的方法?
当前回答
从ES6开始,你可以使用模板字符串使它更短:
var now = new Date();
var todayString = `${now.getFullYear()}-${now.getMonth()}-${now.getDate()}`;
这个解决方案没有零垫。看看其他好的答案,看看如何做到这一点。
其他回答
const date = new Date()
console.log(date.toISOString().split('T')[0]) // 2022-12-27
日期短代码拯救!
const dateShortcode = require('date-shortcode')
dateShortcode.parse('{YYYYMMDD}', new Date())
//=> '20180304'
这段代码修复了Pierre Guilbert的答案:
(10000年后依然有效)
YYYYMMDD=new Date().toISOString().slice(0,new Date().toISOString().indexOf("T")).replace(/-/g,"")
有些日期=新日期(); =某物。 游戏机。log (dateFormated);
这个帖子中最受欢迎的答案的简化版本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;
}