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

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

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

  1. [[email protected].io]# cat bj_time.go
  2. var tz = "Asia/Shanghai"
  3. func getBjNow() time.Time {
  4. now := time.Now().UTC()
  5. loc, err := time.LoadLocation(tz)
  6. if err != nil {
  7. panic(err)
  8. }
  9. bjNow := now.In(loc)
  10. return bjNow
  11. }

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

Ref