PST到UTC在Golang中解析时间

时间:2017-02-17 07:11:36

标签: 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())

}

输出是:

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

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

2 个答案:

答案 0 :(得分:4)

time.Parse()的文档说:

  

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

因此,系统不知道&#34; PST&#34;是。对我来说,系统也不知道IST是什么。您可以检查支持的位置,如下所示:

package main

import (
    "fmt"
    "time"
)

func main() {
    for _, name := range []string{"MST", "UTC", "IST", "PST", "EST", "PT"} {
        loc, err := time.LoadLocation(name)
        if err != nil {
            fmt.Println("No location", name)
        } else {
            fmt.Println("Location", name, "is", loc)
        }
    }
}

我的系统输出:

Location MST is MST
Location UTC is UTC
No location IST
No location PST
Location EST is EST
No location PT

答案 1 :(得分:4)

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

输出:

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

Full code on the Go Playground

相关问题