go - 获取完整的 UTC 偏移量格式

标签 go time timezone timezone-offset

我需要获取某个位置的 UTC 偏移量。我对不同值的结果不一致感到困扰。我只需要获取格式为 +HHMM 的值(例如,+0100 表示“欧洲/罗马”)。

func main() {
    loc, _:= time.LoadLocation("Asia/Kathmandu")
    offset, others:= time.Now().In(loc).Zone()
    fmt.Println(offset, others)
}

Playground

我得到的:

  • “亚洲/加德满都”:+0545(适合)
  • “亚洲/胡志明市”:+07(应该是+0700)
  • “美国/凤凰城”:MST(应为 -0700)
  • “欧洲/罗马”:CET(应该是+0100)

Reference Timezone country names

最佳答案

您正在使用的 Zone() 方法有效 exactly as advertized .

Zone computes the time zone in effect at time t, returning the abbreviated name of the zone (such as "CET") and its offset in seconds east of UTC.

更好的方法是使用 Format方法。像这样的东西:

zone := time.Now().In(loc).Format("-0700")

当然,请注意:由于夏令时,即使这样也不会 100% 一致。

关于go - 获取完整的 UTC 偏移量格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54547840/

相关文章:

go - 如果我正确使用 channel ,我是否需要使用互斥体?

再会!在这个程序中,我制作了包括 Handle 函数的餐厅菜单。我无法将数组 : Name, Price 与函数 getall 和 get 连接起来

go - 为什么地址大小不同? (0x206a10 - 0x104382e0)

excel - 基于 24 小时的频率分布

javascript - JS : sort array on date and time

ruby - 如何将时间字符串解析为特定时区?

recursion - 递归遍历嵌套结构

Java getTime() 从 `time with time zone` 获取时间不正确

ruby-on-rails - Rails Time.zone 解析没有按预期工作

c# - .NET NodaTime 如何创建自定义时区?