【问题标题】:How to get UTC time difference for a given country? [duplicate]如何获取给定国家/地区的 UTC 时差? [复制]
【发布时间】:2020-04-12 17:24:13
【问题描述】:

我正在尝试获取给定国家/地区的 GMT 时差。

但我得到错误的结果,代码为悉尼生成 8 小时而不是正确的 10

如何解决?

const country = "Australia/Sydney"
const utc_ms = Date.now()
const local_s = new Date(utc_ms).toLocaleString("en-US", {timeZone: country})
const local_ms = (new Date(local_s)).getTime()
const diff = (local_ms - utc_ms)/1000/60/60 // => 8 hours

更新

问题似乎是缺少本地偏移量,下面似乎是正确的代码。如果您知道较短的版本,请分享您的答案。

const country = "Australia/Sydney"

function timezone_offset_min(country: string) {
  const local_d = new Date()
  const remote_str = local_d.toLocaleString("en-US", { timeZone: country })
  const local_ms = local_d.getTime()
  const remote_ms = (new Date(remote_str)).getTime()
  const local_remote_offset = Math.round((local_ms - remote_ms) / (60 * 1000))
  const local_offset = new Date().getTimezoneOffset()
  return local_remote_offset + local_offset
}

console.log(timezone_offset_min(country))

【问题讨论】:

  • 请查看重复链接。我在那里为我的答案添加了一个不需要 Moment 的解决方案。它与您的方法类似,但更强大。
  • @MattJohnson-Pint 谢谢

标签: javascript time timezone


【解决方案1】:

尝试使用 moment.js。有关详细说明,此问题的答案已发布Here。 希望这篇文章能帮助解决这个问题。

【讨论】:

  • 谢谢,好像我错过了本地时间偏移,我更新了代码,现在可以正常工作了:)
  • 酷。很高兴听到这个消息:-)
  • 嗨。不鼓励仅链接的答案。我同意您链接的帖子很有用,但将来请投票以关闭为重复,或在问题的 cmets 中引用该帖子。谢谢。
  • 当然@MattJohnson-Pint。我会记住这一点。感谢您的提醒。
猜你喜欢
  • 1970-01-01
  • 2021-04-18
  • 1970-01-01
  • 1970-01-01
  • 2011-12-20
  • 1970-01-01
  • 2022-01-19
  • 2011-09-25
相关资源
最近更新 更多