且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Moment.js将系统日期转换为ISO格式

更新时间:2023-11-29 12:24:22

文档.但是,它们很长,所以这里是细节:

This is pretty well covered in the docs. But, they're long, so here's the specifics:

由于某些原因,momentjs对ISO 8601的定义不同于 ECMAScript 一个,因此它不是内置的.格式为YYYY-MM-DDTHH:mm:ss.sssZ,并且必须采用UTC(Z表示此格式).

For some reason, momentjs's definition of ISO 8601 differs from the ECMAScript one, so it isn't built in. The format is YYYY-MM-DDTHH:mm:ss.sssZ and it must be in UTC (the Z denotes this).

因此, moment().utc() 确保时区正确.

So, moment().utc() makes sure the timezone is correct.

然后格式化它:

moment().utc().format("YYYY-MM-DDTHH:mm:ss.SSS[Z]");
// 2015-02-02T21:38:04.092Z

Z用方括号括起来.我们可以安全执行此操作,因为我们强制执行UTC.

The Z is escaped with square brackets. We can do this safely because we forced UTC.

其余字符根据格式表表示各种时间元素.

The rest of the characters denote various time elements according to the format table.

您还可以按照RobG的说明进行操作,并使用本地日期对象.如果您需要片刻:

You could also do what RobG said and use the native date object. In case you are starting with a moment:

moment().toDate().toISOString( )
// 2015-02-02T21:40:06.395Z