知道UTC时间和时间偏移量时如何设置Go时间值的区域?

chm*_*ike 3 timezone go

我有一个 UTC 时间和一个以秒为单位的时间偏移,需要返回相应的 Go 时间值。

使用 time.Unix() 函数实例化 UTC 时间值很简单。但是要设置Zone,我需要确定time.Location。

在知道 UTC 时间和时间偏移量时如何找到 time.Location?

Jim*_*imB 5

如果没有在时区数据库中查找的实际条目,您就无法知道时间的真实位置。如果您只想使用偏移量,则可以使用创建固定位置time.FixedZone

edt := time.FixedZone("EDT", -60*60*4)
t, _ := time.ParseInLocation("02 Jan 06 15:04", "15 Sep 17 14:55", edt)
fmt.Println(t)

// 2017-09-15 14:55:00 -0400 EDT
Run Code Online (Sandbox Code Playgroud)

您可以选择指定一个不存在的区域名称,或者根本不指定,只要您使用的输出格式不需要。

minus4 := time.FixedZone("", -60*60*4)
t, _ = time.ParseInLocation("02 Jan 06 15:04", "15 Sep 17 14:55", minus4)
fmt.Println(t.Format(time.RFC3339))

// 2017-09-15T14:55:00-04:00
Run Code Online (Sandbox Code Playgroud)