Golang 中 PST 到 UTC 时间的解析

Cod*_*tor 4 go

我试图将时间从 PST 转换为 UTC 时区,但看到了一些意想不到的结果,而 IST 到 UTC 工作正常:

package main

import (
    "fmt"
    "time"
)

func main() {

    const longForm = "2006-01-02 15:04:05 MST"
    t, err := time.Parse(longForm, "2016-01-17 20:04:05 IST")
    fmt.Println(t, err)
    fmt.Printf("IST to UTC: %v\n\n", t.UTC())

    s, err1 := time.Parse(longForm, "2016-01-17 23:04:05 PST")
    fmt.Println(s, err1)
    fmt.Printf("PST to UTC: %v\n\n", s.UTC())

}
Run Code Online (Sandbox Code Playgroud)

输出是:

2016-01-17 20:04:05 +0530 IST <nil>
IST to UTC: 2016-01-17 14:34:05 +0000 UTC

2016-01-17 23:04:05 +0000 PST <nil>
PST to UTC: 2016-01-17 23:04:05 +0000 UTC
Run Code Online (Sandbox Code Playgroud)

当对 IST 进行解析时,它会显示+0530,而对于 PST 会显示+0000并且在 UTC 中它会打印与PST 中相同的 HH:MM:SS (23:04:05) 值。我在这里错过了什么吗?

dol*_*men 7

time.Parse()的文档说:

如果区域缩写未知,Parse 会将时间记录为在具有给定区域缩写和零偏移量的制造位置。这种选择意味着可以使用相同的布局无损地解析和重新格式化这样的时间,但表示中使用的确切时刻将因实际区域偏移而有所不同。为避免此类问题,请首选使用数字区域偏移的时间布局,或使用 ParseInLocation。

以下是使用方法ParseInLocation

IST, err := time.LoadLocation("Asia/Kolkata")
if err != nil {
    fmt.Println(err)
    return
}
PST, err := time.LoadLocation("America/Los_Angeles")
if err != nil {
    fmt.Println(err)
    return
}

const longForm = "2006-01-02 15:04:05 MST"
t, err := time.ParseInLocation(longForm, "2016-01-17 20:04:05 IST", IST)
fmt.Println(t, err)
fmt.Printf("IST to UTC: %v\n\n", t.UTC())

s, err1 := time.ParseInLocation(longForm, "2016-01-17 23:04:05 PST", PST)
fmt.Println(s, err1)
fmt.Printf("PST to UTC: %v\n\n", s.UTC())
Run Code Online (Sandbox Code Playgroud)

输出:

2016-01-17 20:04:05 +0530 IST <nil>
IST to UTC: 2016-01-17 14:34:05 +0000 UTC

2016-01-17 23:04:05 -0800 PST <nil>
PST to UTC: 2016-01-18 07:04:05 +0000 UTC
Run Code Online (Sandbox Code Playgroud)

Go Playground 上的完整代码