Moment.js格式化矩对象并保持偏移量
我有一个momentjs对象,该对象持有带有偏移量的日期时间.此刻对象是通过其字符串表示形式创建的:
I have a momentjs object that hold a datetime with an offset. This moment object was created from its string representation:
var x = moment("2017-02-08T04:11:52+6:00")
使用该对象之后,我想从该时刻对象获得相同的文本表示形式.
After working with the object, I would like to get the same textual representation from the moment object.
尝试格式化对象时得到以下结果:
I get the following results when trying to format the object:
-
x.format()
=>"2017-02-08T04:11:52+14:00"
-
moment.parseZone(x).format("YYYY-MM-DDTHH:mm:ssZ")
=>"2017-02-07T14:11:52+00:00"
-
x.format()
=>"2017-02-08T04:11:52+14:00"
-
moment.parseZone(x).format("YYYY-MM-DDTHH:mm:ssZ")
=>"2017-02-07T14:11:52+00:00"
如何格式化我的矩对象,使我再次具有完全相同的表示形式?
How can I format my moment object such that I have the exact same representation again?
几件事:
-
您的输入是非标准的,因为您已将偏移量指定为
+6:00
. ISO8601格式在小时和分钟偏移量中都需要两位数字. (应该为+06:00
.对于此答案的其余部分,我认为这是一个错字.)
Your input is nonstandard because you've specified the offset as
+6:00
. The ISO8601 format requires two digits in both hours and minutes offset. (It shouold be+06:00
. For the rest of this answer, I'll assume that's a typo.)
创建时刻时,您将丢失原始偏移,因为您正在通过调用moment(...)
调整到本地时区.因此,它在x
中不存在,至少不是以您可以检索它的方式.
You're losing the original offset when you create the moment, because you are adjusting to the local time zone by calling moment(...)
. Therefore it doesn't exist in x
, at least not in a way you can retrieve it.
通常,应将parseZone
传递给字符串,而不是Moment
对象.
In general, parseZone
should be passed a string, not a Moment
object.
您当然可以按照要求设置格式,只要您首先正确解析即可.您甚至不需要指定格式字符串,因为您要查找的是默认格式.
You certainly can format as you asked, as long as you have parsed correctly to begin with. You don't even need to specify a format string, as the one you're looking for is the default.
var str1 = "2017-02-08T04:11:52+06:00";
var mom = moment.parseZone(str1);
var str2 = mom.format(); // "2017-02-08T04:11:52+06:00"