douxiangdiao6348
2015-04-12 18:42 浏览 23
已采纳

在Go中,给定位置名称,我们如何确定该位置的当前时间? [关闭]

We can't use the offset returned by Zone():

package main

import "fmt"
import "time"

func main() {
    loc, _ := time.LoadLocation("America/Los_Angeles")
    t := time.Date(2015,04,12,19,23,0,0,loc)
    t2 := time.Date(2015,03,1,19,23,0,0,loc)
    _, offset := t.Zone()
    _, offset2 := t.Zone()
    fmt.Printf("t1: %v  offset: %d
", t, offset)
    fmt.Printf("t2: %v  offset: %d
", t2, offset2)
}

This returns:

t1: 2015-04-12 19:23:00 -0700 PDT  offset: -25200
t2: 2015-03-01 19:23:00 -0800 PST  offset: -25200

The offset does not reflect daylight savings. Is parsing manually the offset after formatting a time instance the only option (-0700 and -0800)?

We can retrieve the current time with time.Now(), but using .In() simply changes the location without adjusting the hours and minutes.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答 默认 最新

  • 已采纳
    doujiao4705 doujiao4705 2015-04-12 19:28

    Fix the bug in your program. For example,

    package main
    
    import "fmt"
    import "time"
    
    func main() {
        loc, _ := time.LoadLocation("America/Los_Angeles")
        t := time.Date(2015, 04, 12, 19, 23, 0, 0, loc)
        t2 := time.Date(2015, 03, 1, 19, 23, 0, 0, loc)
        _, offset := t.Zone()
        _, offset2 := t2.Zone()
        fmt.Printf("t1: %v  offset: %d
    ", t, offset)
        fmt.Printf("t2: %v  offset: %d
    ", t2, offset2)
    }
    

    Output:

    t1: 2015-04-12 19:23:00 -0700 PDT  offset: -25200
    t2: 2015-03-01 19:23:00 -0800 PST  offset: -28800
    
    点赞 评论 复制链接分享

相关推荐