2015-04-12 106 views
-3

我們不能使用由區()的返回偏移:在Go中,給定位置名稱,我們如何確定該位置的當前時間?

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\n", t, offset) 
    fmt.Printf("t2: %v offset: %d\n", t2, offset2) 
} 

這將返回:

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

偏移量並不反映夏令時。 手動解析格式化時間實例後的偏移量是唯一選項(-0700和-0800)?

我們可以用time.Now()來檢索當前時間,但是使用.In()只是在不調整小時和分鐘的情況下更改位置。

回答

3

修復程序中的錯誤。例如,

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\n", t, offset) 
    fmt.Printf("t2: %v offset: %d\n", t2, offset2) 
} 

輸出:

t1: 2015-04-12 19:23:00 -0700 PDT offset: -25200 
t2: 2015-03-01 19:23:00 -0800 PST offset: -28800 
相關問題