将时区解析为Go中的Location结构

时间:2018-03-03 13:59:21

标签: go timezone

考虑到EDT或CEST这样的时区有没有办法让time.Location引用与func (t Time) In(loc *Location) Time一起使用?

可以初始化例如CEST与time.LoadLocation("Europe/Berlin"),但如何对实际时区表示法做同样的事情?

鉴于@Svip非常有见地的评论是否有任何合理的方式来返回代表性位置列表?这是WET返回,例如[Europe/London, Atlantik/Reykjavík]。所有其他WET位置将遵循与这两个位置相同的时区安排。

2 个答案:

答案 0 :(得分:2)

存在一个包 github.com/tkuchiki/go-timezone 提供区域缩写和位置之间的映射。查看它的 timezones.go

然而,正如评论者所指出的,缩写的时区名称是不明确的,最好完全避免用户输入此类名称。正如其他问题(Why doesn't Go's time.Parse() parse the timezone identifier?How to properly parse timezone codes)中提到的,在解析时间时,Go 正确解析缩写时区,当它匹配机器运行代码的本地时区和 UTC 时区。根据我的经验,所有其他人都没有正确解析。

答案 1 :(得分:2)

可以选择解析给定位置的时间。 (https://golang.org/pkg/time/#LoadLocation)

type CustomTime struct {
    time.Time
}

const ctLayout = "Jan 2, 2006 at 3:04pm (MST)"

func (ct *CustomTime) UnmarshalJSON(b []byte) (err error) {
    s := strings.Trim(string(b), "\"")
    if s == "null" {
        ct.Time = time.Time{}
        return
    }
    location, err := time.LoadLocation("Local")
    if err != nil {
        return err
    }
    ct.Time, err = time.ParseInLocation(ctLayout, s, location)
    return err
}
相关问题