gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 18:54:31 27 4
gpt4 key购买 nike

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

在我调用的模块的 run 方法中

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 中解析给定的字符串,而不是在调用之前通过默认设置中的 Locale 设置的 en-GB 。我在配置/设置过程中是否遗漏了任何内容,导致此功能无法正常工作?我还检查了变量的 _locale 属性。 mom._locale 设置为 en-gb,我可以看到 L、LL、LLL 等格式都是 en-GB 格式的值(因为它们应该是这样)。

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

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

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

最佳答案

使用任何最新版本的 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.

enter image description here

除非您指定格式字符串,否则 MomentJS 依赖于 Date 对象的解析,不幸的是,无论区域设置如何,Date 对象都会使用 的字符串/,假设为美国格式。 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.

关于javascript - MomentJs 输出的 toDate() 日期不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33893037/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com