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

前端 未结 2 1930
有刺的猬
有刺的猬 2020-12-07 03:12

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

相关标签:
2条回答
  • 2020-12-07 03:23

    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
    
    0 讨论(0)
  • 2020-12-07 03:31
    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())
        }
    }
    
    0 讨论(0)
提交回复
热议问题