【问题标题】:How do you convert a time offset to a location/timezone in Go如何将时间偏移量转换为 Go 中的位置/时区
【发布时间】:2019-03-29 06:21:31
【问题描述】:

给定一个任意时间偏移,如何创建一个可用的time.Location 对象来表示该时间偏移?

以下code 使用偏移量解析时间,但fmt.Println(t.Location()) 随后不返回任何信息:

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())
}

游乐场:https://play.golang.org/p/j_E28qJ8Vgy

基本上我有一些带有时间偏移的时间数据,但没有位置数据,我想创建一个time.Location 对象以确保记录GMT 偏移。然后能够输出相对于最终用户实际位置的时间偏移量。

【问题讨论】:

  • 当您说“相对于最终用户的实际位置时间偏移”时,您的意思是指他们的本地时间,包括夏令时?如果是这样 - 那是不可能的(用任何语言)。换句话说,如果所有的都是UTC+2,那么你就无法知道它是属于Africa/Cairo还是Asia/Jersalem还是Europe/Helsinki,还是其他各种地方,可能在UTC+1,也可能不在UTC +2 或 UTC+3 在给定的时间点。

标签: go timezone


【解决方案1】:

用途:

loc := time.FixedZone("UTC+11", +11*60*60)

然后设置到这个位置:

t = t.In(loc)

试试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())
}

输出:

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())
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-29
      • 1970-01-01
      • 2014-07-22
      • 1970-01-01
      • 2021-10-16
      • 2020-01-26
      • 1970-01-01
      相关资源
      最近更新 更多