douguwo2275 2019-03-29 06:21
浏览 218
已采纳

如何在Go中将时间偏移转换为位置/时区

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.

  • 写回答

2条回答 默认 最新

  • doufu3718 2019-03-29 07:48
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来