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


当前回答

如果你不需要一个纯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,'')

这里很多答案都使用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,""))

@o-o解对我没用。 我的解决方案如下:

Date.prototype.yyyymmdd = function() {
  var mm = this.getMonth() + 1; // getMonth() is zero-based
  var dd = this.getDate();
  var ret = [this.getFullYear(), (mm<10)?'0':'', mm, (dd<10)?'0':'', dd].join('');

  return ret; // padding
};

我试图写一个简单的库操作JavaScript日期对象。你可以试试这个。

var dateString = timeSolver.getString(date, "YYYYMMDD")

Libarary: https://github.com/sean1093/timeSolver

如果使用AngularJs(最多1.5),你可以使用日期过滤器:

var formattedDate = $filter('date')(myDate, 'yyyyMMdd')