How do you convert a time offset to a location/timezone in Go

大憨熊 提交于 2020-02-10 04:23:30

问题


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.


回答1:


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



回答2:


if len(offset) == 5 {
    hours, ok1 := strconv.ParseInt(offset[:3], 10, 0)
    mins, ok2 := strconv.ParseInt(offset[3:5], 10, 0)
    if ok1 == nil && ok2 == nil {
        t = t.In(time.FixedZone("Fixed", int((hours*60+mins)*60)))
        fmt.Println(t)
        fmt.Println(t.Location())
    }
}


来源:https://stackoverflow.com/questions/55411566/how-do-you-convert-a-time-offset-to-a-location-timezone-in-go

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!