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


当前回答

日期短代码拯救!

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

其他回答

从ES6开始,你可以使用模板字符串使它更短:

var now = new Date();
var todayString = `${now.getFullYear()}-${now.getMonth()}-${now.getDate()}`;

这个解决方案没有零垫。看看其他好的答案,看看如何做到这一点。

另一种方法是使用toLocaleDateString与一个具有大端日期格式标准的地区,如瑞典,立陶宛,匈牙利,韩国,…:

date.toLocaleDateString('se')

删除分隔符(-)只是替换非数字的问题:

登录(新日期)。代表(/ / / D/g, ');

这不会像UTC日期格式那样产生潜在错误:与本地时区的日期相比,UTC日期可能相差一天。

new Date('Jun 5 2016').
  toLocaleString('en-us', {year: 'numeric', month: '2-digit', day: '2-digit'}).
  replace(/(\d+)\/(\d+)\/(\d+)/, '$3-$1-$2');

// => '2016-06-05'

js有很多有用的日期解析方法。

require (" datejs)

(新的日期()).toString(“名称”)

Day.js怎么样?

它只有2KB,你还可以使用dayjs().format('YYYY-MM-DD')。

https://github.com/iamkun/dayjs