奇怪的行为格式化moment.js日期 [英] Strange behavior formatting moment.js date

查看:171
本文介绍了奇怪的行为格式化moment.js日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在追踪我们的应用程序中的一个错误,该错误似乎与moment.js格式有关。

We are tracking down a bug in our application that seemingly is related to moment.js formatting.

这是有问题的调用(在Chrome,FF和Edge中重现) ,供参考):

Here's the problematic call (reproduced in Chrome, FF, and Edge, for reference):

moment('2016-03-13T23:59:59.999-06:00').format('YYYY-MM-DD')

我们的期望:


2016-03-13

2016-03-13

我们得到的结果:


2016-03-14

2016-03-14

这看起来有点儿了这是唯一的日期(到目前为止),我们已经能够重现这一不正确的行为并在当天翻转DST。

This seemingly has something to do with daylight savings time as this is the only date (so far) that we've been able to reproduce this incorrect behavior on and DST flipped on that day.

如果我们将UTC偏移量切换为 -05:00 然后它正常工作。

If we switch the UTC offset to -05:00 then it works properly.

这是一个简单的JSBIN到演示

Here's a simple JSBIN to demonstrate

这里发生了什么?我们如何解决这个问题?

What's going on here? How can we address this?

推荐答案

Moment会将带偏移的日期转换为您所在计算机的本地时区on,如果你使用默认的矩构造函数。

Moment will convert a date with an offset to the local time zone of the computer that you are on, if you use the default moment constructor function.

因此,你的代码按预期工作。日期取自-6并转换为您的本地偏移量。

For this reason, your code is working as expected. The date is taken from -6 and converted to your local offset.

如果要在指定的时区偏移量中使用日期,请使用moment.parseZone:

If you want to use the date in the timezone offset specified, use moment.parseZone:

moment.parseZone('2016-03-13T23:59:59.999-06:00').format()
"2016-03-13T23:59:59-06:00"

如果你想忽略时区offset,并在本地时间工作,指定不包含偏移量的格式。通过这样做,您可以忽略偏移。

If you want to ignore the timezone offset, and work in local time, specify a format that does not include the offset. By doing this, you cause the offset to be ignored.

moment('2016-03-13T23:59:59.999-06:00', 'YYYY-MM-DDTHH:mm:ss.SSS').format()
"2016-03-13T23:59:59-05:00"

请注意,我是UTC-5,偏移量显示为-5,因为我忽略了日期中的偏移量。

Note that I am in UTC-5 and the offset is displayed as -5 because I ignored the offset in the date.

解析指南可能会有所帮助:
http ://momentjs.com/guides/#/parsing/

The parsing guide may be of some help: http://momentjs.com/guides/#/parsing/

这篇关于奇怪的行为格式化moment.js日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆