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


当前回答

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

date.toLocaleDateString('se')

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

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

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

其他回答

纯JS (ES5)解决方案,没有任何可能的日期跳转问题,由date . toisostring()打印UTC:

var now = new Date();
var todayUTC = new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate()));
return todayUTC.toISOString().slice(0, 10).replace(/-/g, '');

这是为了回应@weberste对@Pierre Guilbert的回答的评论。

当我需要这样做时,我通常使用下面的代码。

var date = new Date($.now());
var dateString = (date.getFullYear() + '-'
    + ('0' + (date.getMonth() + 1)).slice(-2)
    + '-' + ('0' + (date.getDate())).slice(-2));
console.log(dateString); //Will print "2015-09-18" when this comment was written

为了解释,.slice(-2)给出了字符串的最后两个字符。

所以无论如何,我们都可以在日期或月份后加上“0”,只要求最后两个,因为这两个总是我们想要的。

所以如果MyDate.getMonth()返回9,它将是:

("0" + "9") // Giving us "09"

加上。slice(-2)就得到了最后两个字符:

("0" + "9").slice(-2)

"09"

但是如果date.getMonth()返回10,它将是:

("0" + "10") // Giving us "010"

所以加上.slice(-2)会得到最后两个字符,或者:

("0" + "10").slice(-2)

"10"

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

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

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

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

[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,'')

原生Javascript:

new Date().toLocaleString('zu-ZA').slice(0,10).replace(/-/g,'');