【问题标题】:Parse dateTime string as UTC将 dateTime 字符串解析为 UTC
【发布时间】:2020-09-27 08:50:25
【问题描述】:

在我尝试过的每个日期时间库中,时区一直很痛苦。那么问题来了,假设您有一个 UTC 日期时间作为字符串提供:2019-06-25T05:00:00Z。如何从中创建 UTC DateTime 对象(我使用 luxon,但答案可以是任何库)?

console.info(luxon.DateTime.fromISO('2019-06-25T05:00:00Z').toSQL());
<script src="https://moment.github.io/luxon/global/luxon.min.js"></script>

当我运行上面的 sn-p 时,我得到:

2019-06-25 09:00:00.000 +04:00 // local timezone

当我需要时:

2019-06-25 05:00:00.000 -00:00 // UTC

【问题讨论】:

  • 看起来你必须告诉它使用 UTC 作为实例的区域。它正确解析字符串,它只是在构建新字符串时使用您的本地时区。我已经更新了我的答案以展示如何做到这一点。

标签: javascript luxon


【解决方案1】:

三种选择:

1) Luxon 的文档说您可以使用fromISO 从中获取DateTime。 解析字符串正确。看起来要按照您想要的方式格式化,您必须告诉它使用区域 UTC,但那是因为它在 输出 上进行格式化:

const {DateTime} = luxon;
console.info(DateTime.fromISO('2019-06-25T05:00:00Z', { zone: "UTC"}).toSQL());
<script src="https://moment.github.io/luxon/global/luxon.min.js"></script>

您也可以在fromISO 的结果上使用setZone("UTC")。

2) JavaScript 的内置 Date 对象会将其解析为 UTC (new Date(yourString)),因为它的格式为 defined in the spec。然后,您可以使用其上的 UTC 方法来获取 UTC 信息(getUTCHours 等),或者您可以使用其上的本地日期/时间方法来获取本地信息(getHours 等)。您还可以使用toISOString 获取UTC 字符串:

console.info(new Date('2019-06-25T05:00:00Z').toISOString());
<script src="https://moment.github.io/luxon/global/luxon.min.js"></script>

3) Moment 也很乐意这样做。

console.info(moment.utc('2019-06-25T05:00:00Z').toISOString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script>

如果您需要 +00:00 而不是 Z,您可以向其发送 replace,或者使用 Luxon 或 Moment,它们提供完整的格式选项。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-26
    • 2014-03-23
    • 2011-07-18
    • 2014-01-17
    • 2013-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多