hey*_*hey 17 time timezone go timezone-offset
如何将UTC时间转换为当地时间?我为当地时间所需的所有国家创建了一张UTC差异地图.然后我将该差异作为持续时间添加到当前时间(UTC)并打印结果,希望这是该特定国家/地区的当地时间.由于某些原因,结果是错误的.例如在匈牙利,有一个小时的差异.知道为什么我的结果不正确吗?
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)
}
Run Code Online (Sandbox Code Playgroud)
One*_*One 27
请记住,操场有时间设置2009-11-10 23:00:00 +0000 UTC,所以它正在工作.
正确的方法是使用time.LoadLocation,这是一个例子:
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)
}
Run Code Online (Sandbox Code Playgroud)
pet*_*rSO 12
你的方法有缺陷.一个国家可以有几个时区,例如美国和俄罗斯.由于夏令时(DST),时区可以有多次,例如匈牙利.匈牙利的UTC为+1:00,DST也是UTC + 2:00.
对于您希望获得给定UTC时间的本地时间的每个位置,请使用IANA(tzdata)时区位置.例如,
package main
import (
"fmt"
"time"
)
func main() {
utc := time.Now().UTC()
fmt.Println(utc)
local := utc
location, err := time.LoadLocation("Europe/Budapest")
if err == nil {
local = local.In(location)
}
fmt.Println("UTC", utc.Format("15:04"), local.Location(), local.Format("15:04"))
local = utc
location, err = time.LoadLocation("America/Los_Angeles")
if err == nil {
local = local.In(location)
}
fmt.Println("UTC", utc.Format("15:04"), local.Location(), local.Format("15:04"))
}
Run Code Online (Sandbox Code Playgroud)
输出:
2014-08-14 23:57:09.151377514 +0000 UTC
UTC 23:57 Europe/Budapest 01:57
UTC 23:57 America/Los_Angeles 16:57
Run Code Online (Sandbox Code Playgroud)
参考文献:
| 归档时间: |
|
| 查看次数: |
30216 次 |
| 最近记录: |