gpt4 book ai didi

go - Golang 中 PST 到 UTC 时间解析

转载 作者:IT王子 更新时间:2023-10-29 01:19:42 25 4
gpt4 key购买 nike

我正在尝试将时间从 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) 与太平洋标准时间一样。我在这里遗漏了什么吗?

最佳答案

time.Parse() 的文档说:

If the zone abbreviation is unknown, Parse records the time as being in a fabricated location with the given zone abbreviation and a zero offset. This choice means that such a time can be parsed and reformatted with the same layout losslessly, but the exact instant used in the representation will differ by the actual zone offset. To avoid such problems, prefer time layouts that use a numeric zone offset, or use 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

关于go - Golang 中 PST 到 UTC 时间解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42291569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com