如何将时间偏移量转换为 Go 中的位置/时区 [英] How do you convert a time offset to a location/timezone in Go
问题描述
给定一个任意时间偏移,如何创建一个可用的 time.Location
对象来表示该时间偏移?
以下代码使用偏移量解析时间,但fmt.Println(t.Location())
随后不返回任何信息:
func main() {偏移量:=+1100"t, err := time.Parse("15:04 GMT-0700","15:06 GMT"+offset)如果错误!= nil {fmt.Println("失败", err)}fmt.Println(t)fmt.Println(t.UTC())fmt.Println(t.Location())}
游乐场:https://play.golang.org/p/j_E28qJ8Vgyp>
基本上我有一些带有时间偏移的时间数据,但没有位置数据,我想创建一个 time.Location
对象以确保记录 GMT 偏移.然后能够输出相对于终端用户实际位置的时间偏移量.
使用:
loc := time.FixedZone("UTC+11", +11*60*60)
然后设置到这个位置:
t = t.In(loc)
试试这个:
主包进口 (fmt"时间")功能主要(){loc := time.FixedZone("UTC+11", +11*60*60)t := time.Now()fmt.Println(t)fmt.Println(t.Location())t = t.In(loc)fmt.Println(t)fmt.Println(t.Location())fmt.Println(t.UTC())fmt.Println(t.Location())}
输出:
2009-11-10 23:00:00 +0000 UTC m=+0.000000001世界标准时间2009-11-11 10:00:00 +1100 UTC+11UTC+112009-11-10 23:00:00 +0000 UTCUTC+11
Given an arbitrary time offset, how does one go about creating a usable time.Location
object that represents that time offset?
The following code parses a time using an offset, but fmt.Println(t.Location())
subsequently returns no information:
func main() {
offset := "+1100"
t, err := time.Parse("15:04 GMT-0700","15:06 GMT"+offset)
if err != nil {
fmt.Println("fail", err)
}
fmt.Println(t)
fmt.Println(t.UTC())
fmt.Println(t.Location())
}
Playground: https://play.golang.org/p/j_E28qJ8Vgy
Basically I have some time data with time offsets, but without location data, I want to create a time.Location
object to ensure the GMT offset is recorded. And then be able to output the time relative to the end users actual location time offset.
Use:
loc := time.FixedZone("UTC+11", +11*60*60)
Then set to this location:
t = t.In(loc)
Try this:
package main
import (
"fmt"
"time"
)
func main() {
loc := time.FixedZone("UTC+11", +11*60*60)
t := time.Now()
fmt.Println(t)
fmt.Println(t.Location())
t = t.In(loc)
fmt.Println(t)
fmt.Println(t.Location())
fmt.Println(t.UTC())
fmt.Println(t.Location())
}
Output:
2009-11-10 23:00:00 +0000 UTC m=+0.000000001
UTC
2009-11-11 10:00:00 +1100 UTC+11
UTC+11
2009-11-10 23:00:00 +0000 UTC
UTC+11
这篇关于如何将时间偏移量转换为 Go 中的位置/时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!