将 UTC 转换为“本地"围棋时间 [英] Convert UTC to "local" time in Go
问题描述
如何将 UTC 时间转换为当地时间?
How can I convert UTC time to local time?
我已经为我需要的所有国家的当地时间创建了 UTC 差异的地图.然后我将该差异作为持续时间添加到当前时间 (UTC) 并打印结果,希望这是该特定国家/地区的当地时间.
I've created a map with the UTC difference for all the countries I need the local time. Then I add that difference as duration to the current time (UTC) and print the result hoping that's the local time of that specific country.
由于某些原因,结果是错误的.例如,与匈牙利 有一个小时的差异.知道为什么我得到的结果不正确吗?
For some reasons the result is wrong. For example with Hungary there is one hour difference. Any idea why I'm getting incorrect results?
package main
import "fmt"
import "time"
func main() {
m := make(map[string]string)
m["Hungary"] = "+01.00h"
offSet, err := time.ParseDuration(m["Hungary"])
if err != nil {
panic(err)
}
t := time.Now().UTC().Add(offSet)
nice := t.Format("15:04")
fmt.Println(nice)
}
推荐答案
请记住,playground 的时间设置为 2009-11-10 23:00:00 +0000 UTC
,所以它正在工作.
Keep in mind that the playground has the time set to 2009-11-10 23:00:00 +0000 UTC
, so it is working.
不过,正确的方法是使用 time.LoadLocation
,这是一个例子:
The proper way is to use time.LoadLocation
though, here's an example:
var countryTz = map[string]string{
"Hungary": "Europe/Budapest",
"Egypt": "Africa/Cairo",
}
func timeIn(name string) time.Time {
loc, err := time.LoadLocation(countryTz[name])
if err != nil {
panic(err)
}
return time.Now().In(loc)
}
func main() {
utc := time.Now().UTC().Format("15:04")
hun := timeIn("Hungary").Format("15:04")
eg := timeIn("Egypt").Format("15:04")
fmt.Println(utc, hun, eg)
}
这篇关于将 UTC 转换为“本地"围棋时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!