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


当前回答

纯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的回答的评论。

其他回答

原生Javascript:

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

console.log(date.toISOString().split('T')[0]) // 2022-12-27

下面是一种更通用的方法,它允许日期和时间组件,并且可以作为数字或字符串进行相同的排序。

根据“Date ISO format”中的数字顺序,转换为本地时区,去掉非数字。例如:

// monkey patch version
Date.prototype.IsoNum = function (n) {
    var tzoffset = this.getTimezoneOffset() * 60000; //offset in milliseconds
    var localISOTime = (new Date(this - tzoffset)).toISOString().slice(0,-1);
    return localISOTime.replace(/[-T:\.Z]/g, '').substring(0,n || 20); // YYYYMMDD
}

使用

var d = new Date();
// Tue Jul 28 2015 15:02:53 GMT+0200 (W. Europe Daylight Time)
console.log(d.IsoNum(8));  // "20150728"
console.log(d.IsoNum(12)); // "201507281502"
console.log(d.IsoNum());   // "20150728150253272"

@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
};

要获得本地日期,YYYYMMDD格式,我使用:

var todayDate = (new Date()).toLocaleString('en-GB').slice(0,10).split("\/").reverse().join("");