gpt4 book ai didi

javascript - 日期转换为本地日期时间

转载 作者:行者123 更新时间:2023-12-03 01:00:30 25 4
gpt4 key购买 nike

我有 UTC 日期变量:

let d = '/Date(1538560800000+0200)/';

我尝试将其转换为本地时间,但没有成功:

moment(accessGroup.TimeOn).toDate() // result: Wed Oct 03 2018 12:00:00 GMT+0200 (Central European Summer Time)
moment(d).local().format("DD-MM-YYYY hh-mm-ss"); // result: "03-10-2018 12-00-00"
moment.utc(d).local().format("DD-MM-YYYY hh-mm-ss"); // result: "03-10-2018 12-00-00"

我想获取本地时间 14:00:00。正确的方法是什么?

最佳答案

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

Moment 接受 ISO 8601 和 RFC 2822 格式的字符串参数,而您输入的 /Date(1538560800000+0200)/ 两者都不是。不过,当您将其传递给 moment 时,它会尝试将其转换为字符串,并最终提取可能的时间戳参数,即 1538560800000。这可以在下面的代码中看到,因为两者最终都是相同的值..

let d = '/Date(1538560800000+0200)/'
moment(d).toString() // Wed Oct 03 2018 12:00:00 GMT+0200
moment(1538560800000).toString() // Wed Oct 03 2018 12:00:00 GMT+0200

1538560800000 转换为 GMT 时为 Wed Oct 03 2018 10:00:00 GMT+0000,因此以下代码的输出..

moment.utc(d).toString() // Wed Oct 03 2018 10:00:00 GMT+0000

因此,在任何情况下您都不会得到 14:00:00 的时间,因为此时间戳并不代表这一点。并且时间戳始终是绝对的(以 GMT 表示),有 no such thing as a local timestamp .

<小时/>

我觉得这里的差距是你对输入字符串的错误解释,你在想..

  • 1538560800000 转换为本地日期时间,即 10 月 3 日 12:00:00(本地)
  • 添加 +0200 小时,即改为 10 月 3 日 14:00:00

但是,阅读它的正确方法是..

  • 1538560800000 转换为日期时间,即 10 月 3 日 10:00:00(绝对/GMT)
  • +0200 表示源的时区,即 GMT+0200

同样,由于上述原因,第一种解释是错误的 - unix 时间戳始终采用 GMT,它们永远不会采用本地时区。

关于javascript - 日期转换为本地日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52645437/

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