我想通过使用golang提供特定位置,将UTC时间转换为本地时间

时间:2017-07-11 07:04:27

标签: go

我是golang开发人员,我正在尝试将UTC时间转换为本地时间但我的代码无效。这是我的代码

utc := time.Now().UTC()
local := utc
location, err := time.LoadLocation("Asia/Delhi")
if err == nil {
   local = local.In(location)
}
log.Println("UTC", utc.Format("15:04"), local.Location(), local.Format("15:04"))

3 个答案:

答案 0 :(得分:4)

您应该重写代码以在错误发生时处理错误。默认执行路径应该没有错误。因此,在time.LoadLocation之后检查是否存在错误:

utc := time.Now().UTC()
local := utc
location, err := time.LoadLocation("Asia/Delhi")
if err != nil {
   // execution would stop, you could also print the error and continue with default values
   log.Fatal(err)
}
local = local.In(location)
log.Println("UTC", utc.Format("15:04"), local.Location(), local.Format("15:04"))

现在你会得到类似这样的错误消息:

cannot find Asia/Delhi in zip file /usr/local/go/lib/time/zoneinfo.zip
panic: time: missing Location in call to Time.In

您必须找到适合您所在位置的时间zome,因为其他人说检查维基百科Storing sensitive data securely in a database

答案 1 :(得分:3)

你在第3行遇到错误,你只是看不到它,因为它避免了if阻止,因此永远不会更新第5行的local变量。

失败的原因是因为“亚洲/德里”不是有效的奥尔森格式。

添加else块并打印出err.Error()

有关有效格式的列表,请参阅以下链接:

https://en.wikipedia.org/wiki/List_of_tz_database_time_zones

答案 2 :(得分:0)

这只是根据您指定的布局将UTC时间字符串转换为本地时间字符串。

func UTCTimeStr2LocalTimeStr(ts, layout string) (string, error) {                                                                  
    timeObject, err := time.Parse(time.RFC3339, ts)
    if err != nil {
        return "", err
    }

    return time.Unix(timeObject.Unix(), 0).Format(layout), nil
}
相关问题