【问题标题】:Moment.js works weirdlyMoment.js 工作异常
【发布时间】:2021-10-14 18:29:09
【问题描述】:

我正在使用 Moment 处理时间,我想要实现的是将本地时间转换为 UTC 时间。我的当地时间是 GMT+5。

所以,这是我的代码:

moment("12:15", "HH a").utc().format("HH")

我期望得到的是19,但我得到的是07。我真的需要你的帮助。我正在使用 moment.js 2.24.0。

【问题讨论】:

  • 07:15 GMT+0 是 12:15 GMT+5 — 这工作正常。
  • 如果你在+5,为什么期望19而不是7? Utc id +0,因此减少了 5 小时。
  • @coll,我的意思是 12:15 是上午,需要 5 个小时,那么 19 是正确的数字吗?对吗?
  • @RaniSharim,我的意思是 12:15 是上午,因此如果我们抽出 5 个小时,那么 19 个小时将是正确的。对吗?
  • @qweeee HH 是 24 小时制

标签: javascript momentjs


【解决方案1】:

使用hh 解析输入的小时数,不要忘记分钟数。

console.log(moment('12:15', 'hh:mm').utc().format('HH'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

由于 Moment 已停产,您应该改用 Luxon。

const { DateTime } = luxon;

console.log(DateTime.fromFormat('12:15', 'hh:mm').toUTC().toFormat('HH'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/2.0.2/luxon.min.js"></script>

【讨论】:

  • 感谢您的回答,但我仍然得到 07,但我认为得到 19 是合乎逻辑的。请你看看 jsfiddle.net/vw81bhsq/43 那里我得到 19 为什么?请记住我的 GMT+5 时区
  • @qweeee 您的 JSFiddle 与您的示例相同。您需要先正确解析。这是你的主要问题。
  • @qweeee 格式字符串中有a,表示上午或下午。由于您输入的时间12:15 没有这样的指示符,所以此刻可能认为您的日期为am。对于 GMT +5,您减去 5 小时以找到 UTC 时间,这意味着 24 - 5 = 19。HH 是 24 小时格式,所以您会看到 19。
猜你喜欢
  • 2013-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多