如何在已知 UTC 时间和时间偏移量的情况下设置 Go 时间值的时区?

huangapple go评论72阅读模式
英文:

How to set the Zone of a Go time value when knowing the UTC time and time offset?

问题

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

使用time.Unix()函数可以轻松实例化UTC时间值。但是要设置时区,我需要确定时间位置。

当我知道UTC时间和时间偏移量时,如何找到时间位置?

英文:

I have an UTC time and a time offset in seconds, and need to return the corresponding Go time value.

It is trivial to instantiate the UTC time value by using the time.Unix() function. But to set the Zone, I need to determine the time.Location.

How can I find the time.Location when knowing the UTC time and time offset ?

答案1

得分: 9

在没有实际的时区数据库条目可供查询的情况下,你无法确定时间的真实位置。如果你只想使用偏移量,可以使用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

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

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
英文:

Without an actual entry to lookup in the time zone database, you can't know the true location for the time. If you want to work with just an offset, you can create a fixed location using 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

You can opt to specify a non-existent zone name, or none at all, as long as the output format you use doesn't require one.

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

huangapple
  • 本文由 发表于 2017年9月16日 02:46:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/46245784.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定