【问题标题】:momentjs switching between timezone with 12 hours or more differencemomentjs 在时区之间切换,时差为 12 小时或更长时间
【发布时间】:2021-10-20 13:11:47
【问题描述】:

我正在使用 moment js 将日期转换为 UTC 像这样

var a = moment.utc('20-Oct-2021').tz('Asia/Kolkata');

a.format()

这个结果2021-10-20T05:30:00+05:30

现在我正在尝试使用来自该时区 Pacific/Auckland 的 Newsland 的访问权限 - 在系统中,我将我的时区更改为 +13。

现在的结果

moment().utc(a).format()

2021-10-21T02:09:12Z

如果您注意到日期是 21 而不是 20,这是实际存储的日期。

面临所有大于 +-12 的问题

【问题讨论】:

  • moment().utc(a) 对我来说似乎不是正确的用法。用moment() 调用utc() 有不同的目的。检查momentjs.com/docs/#/manipulating/utc
  • @alpakyol 正确的做法是什么?

标签: momentjs moment-timezone


【解决方案1】:

更改您的时区不会更改a 的时区,因为它的时区是手动设置的。您需要使用local() 来获取您所在时区的时间。

// Always pass the string format if the string is not an ISO 8601 date
var a = moment.utc('20-Oct-2021', 'DD-MMM-YYYY').tz('Asia/Kolkata');

console.log(a.format());
console.log(a.utc().format()); // in UTC

console.log(a.local().format()); // This is in your timezone

a.tz("Pacific/Auckland"); // Change to Auckland

console.log(a.format()); // Auckland time
console.log(a.local().format()); // In your timezone, as same as above
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.33/moment-timezone-with-data-10-year-range.min.js"></script>

【讨论】:

    猜你喜欢
    • 2019-07-17
    • 2012-04-09
    • 2020-06-09
    • 1970-01-01
    • 2014-10-17
    • 2012-12-01
    • 2013-10-14
    • 2013-08-17
    • 2017-06-27
    相关资源
    最近更新 更多