我有一个日期字符串列表,这些字符串以这种格式出现,没有任何时区或偏移信息:
[
"2019-04-30T12:34:00.000", // In 2019, DST started in March 10, 2019, so this should have the appropriate DST offset
"2017-11-20T13:45:00.000" // In 2017, DST ended on November 5, 2017 so this should have the appropriate standard time offset
]
我知道这些日期和时间是在IANA区域(例如,America/New_York
)创建的,但我不知道如何使用go和time
包动态生成适当的偏移量。
我想过以下几点:
"2019-04-30T12:34:00.000" + "-04:00
)然而,这些解决方案只适用于某些日期,或者逻辑变得非常复杂。
发布于 2020-05-14 21:08:51
我想出了办法
package main
import (
"log"
"time"
)
func main() {
Chicago, _ := time.LoadLocation("America/Chicago")
t := time.Date(2019, time.March, 1, 12, 30, 0, 0, Chicago)
log.Print(t) // 2019-03-01 12:30:00 -0600 CST
log.Print(t.UTC()) // 2019-03-01 18:30:00 +0000 UTC
t = time.Date(2019, time.November, 2, 12, 30, 0, 0, Chicago)
log.Print(t) // 2019-11-02 12:30:00 -0500 CDT
log.Print(t.UTC()) // 2019-11-02 17:30:00 +0000 UTC
}
去操场@ https://play.golang.org/p/nP28y9jSDAk
通过使用自定义布局和time.LoadLocation,一种更加简洁的解决方案
package main
import (
"fmt"
"time"
)
func main() {
Chicago, _ := time.LoadLocation("America/Chicago")
cdt, _ := time.ParseInLocation("2006-01-02T15:04:05.999999", "2019-04-30T12:34:00.000", Chicago)
fmt.Println(cdt)
fmt.Println(cdt.UTC())
cst, _ := time.ParseInLocation("2006-01-02T15:04:05.999999", "2017-11-20T13:45:00.000", Chicago)
fmt.Println(cst)
fmt.Println(cst.UTC())
}
https://stackoverflow.com/questions/61811998
复制相似问题