time.LoadLocation

Go 语言中,时间的时区主要依靠 time.LoadLocation 这个方法:

// LoadLocation returns the Location with the given name.
//
// If the name is "" or "UTC", LoadLocation returns UTC.
// If the name is "Local", LoadLocation returns Local.
//
// Otherwise, the name is taken to be a location name corresponding to a file
// in the IANA Time Zone database, such as "America/New_York".
//
// The time zone database needed by LoadLocation may not be
// present on all systems, especially non-Unix systems.
// LoadLocation looks in the directory or uncompressed zip file
// named by the ZONEINFO environment variable, if any, then looks in
// known installation locations on Unix systems,
// and finally looks in $GOROOT/lib/time/zoneinfo.zip.

获取指定时区的时间

它可以根据你的参数返回对应的时区信息,然后,你只需要通过 time.In(location) 即可获得对应时区的时间了,例如我这里写一个获取北京时间的例子:

[[email protected]]# cat bj_time.go
var tz = "Asia/Shanghai"

func getBjNow() time.Time {
    now := time.Now().UTC()

    loc, err := time.LoadLocation(tz)
    if err != nil {
        panic(err)
    }
    bjNow := now.In(loc)
    return bjNow
}

首先先获取 UTC 时间,然后转换成北京时间,就这么简单。

Ref