我试图使用JS将日期对象转换为YYYYMMDD格式的字符串。有没有比连接Date.getYear(), Date.getMonth()和Date.getDay()更简单的方法?
当前回答
使用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('-');
};
其他回答
如果你不需要一个纯JS的解决方案,你可以使用jQuery UI来做这样的工作:
$.datepicker.formatDate('yymmdd', new Date());
我通常不喜欢导入太多的库。但是jQuery UI非常有用,你可能会在项目的其他地方用到它。
更多示例请访问http://api.jqueryui.com/datepicker/
您可以简单地使用这一行代码来获取日期
var date = new Date().getFullYear() + "-" + (parseInt(new Date().getMonth()) + 1) + "-" + new Date().getDate();
当地时间:
var date = new Date();
date = date.toJSON().slice(0, 10);
UTC时间:
var date = new Date().toISOString();
date = date.substring(0, 10);
在我写这篇文章的时候,日期将在今天2020-06-15打印出来。
toISOString()方法返回ISO标准的日期,YYYY-MM-DDTHH:mm:ss.sssZ
代码采用YYYY-MM-DD格式所需的前10个字符。
如果你想要没有'-'的格式,请使用:
var date = new Date();
date = date.toJSON().slice(0, 10).split`-`.join``;
在.join ' '中,你可以添加空格、点或任何你喜欢的东西。
[day,,month,,year]= Intl.DateTimeFormat(undefined, { year: 'numeric', month: '2-digit', day: '2-digit' }).formatToParts(new Date()),year.value+month.value+day.value
or
new Date().toJSON().slice(0,10).replace(/\/|-/g,'')
Day.js怎么样?
它只有2KB,你还可以使用dayjs().format('YYYY-MM-DD')。
https://github.com/iamkun/dayjs