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


当前回答

我写了一个简单的函数,它可以将Date对象转换为具有日期号、月份号(带零填充)和年份号的可定制顺序的String。您可以将它与您喜欢的任何分隔符一起使用,或者将此参数保留为空以在输出中不显示分隔符。请看一看。

function dateToString(date, $1, $2, $3, separator='') { const dateObj = { date: String(date.getDate()).padStart(2, '0'), month: String(date.getMonth() + 1).padStart(2, '0'), year: date.getFullYear() }; return dateObj[$1] + separator + dateObj[$2] + separator + dateObj[$3]; } const date = new Date(); const dateString1 = dateToString(date, 'year', 'month', 'date'); console.log(dateString1); // Manipulate arguments order to get output you want const dateString2 = dateToString(date, 'date', 'month', 'year', '-'); console.log(dateString2);

其他回答

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

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

使用padStart:

Date.prototype.yyyymmdd = function() {
    return [
        this.getFullYear(),
        (this.getMonth()+1).toString().padStart(2, '0'), // getMonth() is zero-based
        this.getDate().toString().padStart(2, '0')
    ].join('-');
};

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

Dateformat是一个非常常用的包。

使用方法:

从NPM下载并安装dateformat。在你的模块中需要它:

以格式

然后格式化你的东西:

const myYYYYmmddDate = dateformat(new Date(), 'yyyy-mm-dd');

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

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