这个文档提到了时刻。ISO_8601作为格式化选项(从2.7.0 - http://momentjs.com/docs/#/parsing/special-formats/),但这些都不能工作(即使是2.7.0):

var date = moment();
date.format(moment.ISO_8601); // error
moment.format(date, moment.ISO_8601); // error

(http://jsfiddle.net/b3d6uy05/1/)

如何从moment.js中获得ISO 8601 ?


使用不带参数的格式:

var date = moment();
date.format(); // "2014-09-08T08:02:17-05:00"

(http://jsfiddle.net/8gvhL1dz/)

moment().toISOString(); // or format() - see below

http://momentjs.com/docs/#/displaying/as-iso-string/

Update Based on the answer: by @sennet and the comment by @dvlsg (see Fiddle) it should be noted that there is a difference between format and toISOString. Both are correct but the underlying process differs. toISOString converts to a Date object, sets to UTC then uses the native Date prototype function to output ISO8601 in UTC with milliseconds (YYYY-MM-DD[T]HH:mm:ss.SSS[Z]). On the other hand, format uses the default format (YYYY-MM-DDTHH:mm:ssZ) without milliseconds and maintains the timezone offset.

我开了一个问题,因为我认为它会导致意想不到的结果。

如果你只想要日期部分(例如2017-06-27),并且你想让它不管时区和阿拉伯语都能工作,下面是我写的代码:

function isoDate(date) {
    if (!date) {
        return null
    }
    date = moment(date).toDate()

    // don't call toISOString because it takes the time zone into
    // account which we don't want.  Also don't call .format() because it
    // returns Arabic instead of English

    var month = 1 + date.getMonth()
    if (month < 10) {
        month = '0' + month
    }
    var day = date.getDate()
    if (day < 10) {
        day = '0' + day
    }
    return date.getFullYear() + '-' + month + '-' + day
}

香草JS也可以

new Date().toISOString() // "2017-08-26T16:31:02.349Z"

当你使用Mongoose将日期存储到MongoDB时,你需要使用toISOString(),因为所有的日期都存储为以毫秒为单位的ISOdates。

moment.format() 

2018-04-17T20:00:00Z

moment.toISOString() -> USE THIS TO STORE IN MONGOOSE

2018-04-17T20:00:00.000Z
var x = moment();

//date.format(moment.ISO_8601); // error

moment("2010-01-01T05:06:07", ["YYYY", moment.ISO_8601]);; // error
document.write(x);

2020年的答案(包括时区支持)

我们遇到的问题是,默认情况下,isostring没有本地化到您的时区。所以,这有点俗气,但这是我们最终解决这个问题的方法:

/**导入Moment用于时间实用程序。* / Const moment = require("moment-timezone") 时刻().tz(美国/芝加哥).format () //**现在返回ISO格式的中央时间*/ 导出函数getNowISO() { 返回“${时刻().toISOString(真正的)。substring (0, 23)} Z” }

这将为您留下一个精确的iso格式的本地化字符串。

重要提示:Moment现在建议在新项目中使用其他包。

var date = moment(new Date(), moment.ISO_8601);
console.log(date);

如果需要格式化字符串:YYYY-MM-DDTHH:mm:ssZ

var date = moment();
console.log(date.format("YYYY-MM-DDTHH:mm:ssZ"));