Javascript 使用 momentjs 将系统日期转换为 ISO 格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28277272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert system date to ISO format using momentjs
提问by user1184100
I'm trying to convert system date to ISO format in below fashion using momentjs
我正在尝试使用 momentjs 以以下方式将系统日期转换为 ISO 格式
2015-02-17T19:05:00.000Z
I'm however unable to find the parameter that I need to use to get it in the format which I want. I tried below piece of code..
但是,我无法找到以我想要的格式获取它所需的参数。我试过下面的一段代码..
moment().format("YYYY-MM-DD HH:mm Z");
I get output as 2015-02-02 17:24+05:30.
我得到的输出为 2015-02-02 17:24+05:30。
How can I get it as 2015-02-02T17:24:00.000Z
我怎样才能得到它 2015-02-02T17:24:00.000Z
回答by DanielST
This is pretty well covered in the docs. But, they're long, so here's the specifics:
这在docs 中有很好的介绍。但是,它们很长,所以这是细节:
For some reason, momentjs's definition of ISO 8601 differs from the ECMAScriptone, so it isn't built in. The format is YYYY-MM-DDTHH:mm:ss.sssZand it must be in UTC (the Zdenotes this).
出于某种原因,momentjs 对 ISO 8601 的定义与ECMAScript的定义不同,因此它不是内置的。格式是YYYY-MM-DDTHH:mm:ss.sssZ并且必须是 UTC(Z表示 this)。
So, moment().utc()makes sure the timezone is correct.
因此,请moment().utc()确保时区正确。
Then formatit:
然后格式化:
moment().utc().format("YYYY-MM-DDTHH:mm:ss.SSS[Z]");
// 2015-02-02T21:38:04.092Z
The Zis escaped with square brackets. We can do this safely because we forced UTC.
该Z是逃脱方括号。我们可以安全地做到这一点,因为我们强制使用 UTC。
The rest of the characters denote various time elements according to the format table.
其余字符根据格式表表示各种时间元素。
You could also do what RobG said and use the native date object. In case you are starting with a moment:
您也可以按照 RobG 所说的去做并使用本机日期对象。如果您从片刻开始:
moment().toDate().toISOString( )
// 2015-02-02T21:40:06.395Z

