toDate() 的 MomentJs 输出日期不正确

MomentJs output Date of toDate() is incorrect

我已经开始在一个 Angular/Typescript 项目中使用 momentJs。 (包括在内,以防它以任何方式相关,尽管我非常怀疑)

在我调用的模块的 运行 方法中

moment.locale(window.navigator.language);

在我的实例中,它正确地将区域设置设置为 en-GB。更进一步,我使用 moment 来解析 GB 时间。

执行以下操作时:

var mom = moment("24/11/2015 00:00:00");

例如。这会使用全局瞬间设置的默认值填充一个新的瞬间对象(如果我理解它应该如何正确工作)。妈妈的日期设置为 2016-12-11T00:00:00.000Z。这显然意味着它在 en-US 中解析了给定的字符串,而不是 en-GB,后者是在此调用之前通过 Locale 在默认设置中设置的。我在 configuration/setup 的那一刻错过了什么会使它不起作用吗? 我还检查了变量的 _locale 属性。 mom._locale 设置为 en-gb,我可以看到 L、LL、LLL 等格式都是 en-GB 格式的值(它们应该是)。

运行宁mom.toDate();不出所料 returns moment 对象内部存储的 2016 年日期。

一些我忘记包括的杂项信息:

我正在使用 NuGet 的最新版 momentjs(撰写本文时为 2.10.6 版),并且我在 HTML[=12= 中包含了 moment-with-locales.js ]

您最好直接将格式传递给 moment 并事先验证字符串。这将最终减少您需要进行的调试工作,让您立即 运行。

var mom = moment("24/11/2015 00:00:00", "DD/MM/YYYY HH:mm:ss");

您可以尝试新的(ish)Intl API,但浏览器支持有限(IE11+),所以我建议让用户 select 在下拉列表中显示月份或其他强制他们输入某种方式。

使用任何最新版本的 MomentJS,您应该会在控制台中看到原因:

Deprecation warning: moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to https://github.com/moment/moment/issues/1407 for more info.

除非您指定格式字符串,否则 MomentJS 依赖于 Date 对象的解析,不幸的是,无论语言环境如何,Date 对象都将使用 / 的字符串假设U.S。格式。 Date.

有很多很多不合适的事情之一

您需要使用格式字符串,或提供 Date 使用的简化 ISO-8601 格式的字符串。来自 Parse > String:

When creating a moment from a string, we first check if the string matches known ISO 8601 formats, then fall back to new Date(string) if a known format is not found.

var day = moment("1995-12-25");

Warning: Browser support for parsing strings is inconsistent. Because there is no specification on which formats should be supported, what works in some browsers will not work in other browsers.

For consistent results parsing anything other than ISO 8601 strings, you should use String + Format.

所以我通过从那一刻获取语言环境数据并将其传递到格式参数来解决这个问题。考虑到“24/11/2015 00:00:00”的示例输入,我将按如下方式构建我的格式:

var format = moment.localeData().longDateFormat('L') + " " + moment.localeData().longDateFormat("LTS");

这会生成 "DD/MM/YYYY HH:mm:ss" 的格式掩码。

您可以混合和匹配您想要的任何格式,这将是特定于您设置 moment.locale("") 的区域设置(假设您已经立即设置了区域设置信息)

这是一个疯狂的解决方法,令我惊讶的是,moment 在解析时并未将区域设置信息假定为默认信息。 TJCrowder 在 Github 上提出了一个问题,我建议任何关心的人都应该发表评论。 https://github.com/moment/moment/issues/2770