我试图使用JS将日期对象转换为YYYYMMDD格式的字符串。有没有比连接Date.getYear(), Date.getMonth()和Date.getDay()更简单的方法?
当前回答
很好,很简单:
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);
其他回答
const date = new Date()
console.log(date.toISOString().split('T')[0]) // 2022-12-27
这里很多答案都使用toisostring函数。这个函数在输出之前将时间转换为zulu时间,这可能会导致问题。
function datestring(time) {
return new Date(time.getTime() - time.getTimezoneOffset()*60000).toISOString().slice(0,10).replace(/-/g,"")
}
mydate = new Date("2018-05-03")
console.log(datestring(mydate))
datestring函数修复了时区问题,或者更好的是,你可以通过使用zulu时间来避免整个问题:
mydate = new Date("2018-05-03Z")
// mydate = new Date(Date.UTC(2018,5,3))
console.log(mydate.toISOString().slice(0,10).replace(/-/g,""))
有些日期=新日期(); =某物。 游戏机。log (dateFormated);
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();
Day.js怎么样?
它只有2KB,你还可以使用dayjs().format('YYYY-MM-DD')。
https://github.com/iamkun/dayjs