Momentjs 格式化 moment 对象并保留偏移量。

10

我有一个 momentjs 对象,它包含带有偏移量的日期时间。这个 moment 对象是从其字符串表示创建的:

var x = moment("2017-02-08T04:11:52+6:00")

使用该对象后,我想从moment对象中获取相同的文本表示。

尝试格式化对象时,我得到以下结果:

  • 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"

如何格式化我的moment对象,以便再次获得完全相同的表示?


你可能认为这种用例已经被Moment时区覆盖了,但从文档上看并不是这样。并不是很令人印象深刻。 - T.J. Crowder
x.format() 给了我 (moment 2.17.1, tz Europe/Rome) Invalid date 和 _Deprecation warning_。我担心问题在于你的输入字符串中偏移量为 +6:00 而不是 +06:00(两位数字)。 - VincenzoC
在momentjs网站上提供的日期无效。您能确认一下吗? - kawadhiya21
只需尽可能获得最接近的结果,然后使用字符串操作和一点正则表达式稍后自行修复。 - Nonemoticoner
2
@无表情符号 - 这太荒谬了。 - Matt Johnson-Pint
1个回答

8
一些事项:
  • 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.)

  • 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.

  • 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"
    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接