我试图使用JS将日期对象转换为YYYYMMDD格式的字符串。有没有比连接Date.getYear(), Date.getMonth()和Date.getDay()更简单的方法?


当前回答

如果你不介意包含一个额外的(但很小的)库,Sugar.js为在JavaScript中处理日期提供了很多不错的功能。 格式化日期,使用format函数:

new Date().format("{yyyy}{MM}{dd}")

其他回答

Dateformat是一个非常常用的包。

使用方法:

从NPM下载并安装dateformat。在你的模块中需要它:

以格式

然后格式化你的东西:

const myYYYYmmddDate = dateformat(new Date(), 'yyyy-mm-dd');

有些日期=新日期(); =某物。 游戏机。log (dateFormated);

日期短代码拯救!

const dateShortcode = require('date-shortcode')
dateShortcode.parse('{YYYYMMDD}', new Date())
//=> '20180304'

如果你不需要一个纯JS的解决方案,你可以使用jQuery UI来做这样的工作:

$.datepicker.formatDate('yymmdd', new Date());

我通常不喜欢导入太多的库。但是jQuery UI非常有用,你可能会在项目的其他地方用到它。

更多示例请访问http://api.jqueryui.com/datepicker/

对公认答案的一点变化:

函数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 ())