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


当前回答

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

date.toLocaleDateString('se')

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

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

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

其他回答

这个家伙这里=> http://blog.stevenlevithan.com/archives/date-time-format写了一个格式()函数Javascript的日期对象,所以它可以使用熟悉的文字格式。

如果你需要在应用程序的Javascript中使用完整的日期格式,请使用它。否则,如果你想做的是一次性的,那么连接getYear(), getMonth(), getDay()可能是最简单的。

以下是对https://stackoverflow.com/users/318563/o-o的回答的一点改进

Date.prototype.ddmmyyyy = function(delimiter) {
    var yyyy = this.getFullYear().toString();
    var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
    var dd  = this.getDate().toString();
    return (dd[1]?dd:"0"+dd[0]) + delimiter + (mm[1]?mm:"0"+mm[0]) + delimiter +yyyy  ; // padding
};

希望对大家有所帮助!

:)

原生Javascript:

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

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

根据“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"

似乎mootools提供了Date().format(): https://mootools.net/more/docs/1.6.0/Types/Date

但我不确定是否值得只针对这个特定的任务。