我需要获取某个位置的 UTC 偏移量。我对不同值的结果不一致感到困扰。我只需要获取格式为 +HHMM
的值(例如,+0100
表示“欧洲/罗马”)。
func main() {
loc, _:= time.LoadLocation("Asia/Kathmandu")
offset, others:= time.Now().In(loc).Zone()
fmt.Println(offset, others)
}
我得到的:
- “亚洲/加德满都”:
+0545
(适合) - “亚洲/胡志明市”:
+07
(应该是+0700
) - “美国/凤凰城”:
MST
(应为-0700
) - “欧洲/罗马”:
CET
(应该是+0100
)
最佳答案
您正在使用的 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/