将UTC转换为“本地”时间 - 去吧 [英] Convert UTC to "local" time - Go

查看:140
本文介绍了将UTC转换为“本地”时间 - 去吧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将UTC时间转换为当地时间?
我为所有需要当地时间的国家/地区创建了具有UTC差异的地图。然后我将此差异作为持续时间添加到当前时间(UTC),并打印结果,希望这是该特定国家的当地时间。
由于某些原因,结果是错误的。例如,在匈牙利上,有一个小时的差异。

How can I convert UTC time to local time ? 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 on 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)
}


推荐答案

请记住,操场有时间设置为 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆