如何使用特定时区解析时间



我要从字符串中获得一个时间结构。我使用的功能是time.ParseTime(),布局是"2006-01-02 15:04"

当我用任何有效的时间字符串执行函数时,我得到一个指向该时间戳的时间结构体,但它是在UTC。

如何将其更改为不同的时区?要清楚,我想要相同的时间戳,但不同的时区。我不想在时区之间转换;我只是想获得相同的时间对象,但不是UTC。

使用time.ParseInLocation来解析给定位置的时间,当没有给定时区时。time.Local是您的本地时区,将其作为您的Location传入。

package main
import (
"fmt"
"time"
)
func main() {
// This will honor the given time zone.
// 2012-07-09 05:02:00 +0000 CEST
const formWithZone = "Jan 2, 2006 at 3:04pm (MST)"
t, _ := time.ParseInLocation(formWithZone, "Jul 9, 2012 at 5:02am (CEST)", time.Local)
fmt.Println(t)
// Lacking a time zone, it will use your local time zone.
// Mine is PDT: 2012-07-09 05:02:00 -0700 PDT
const formWithoutZone = "Jan 2, 2006 at 3:04pm"
t, _ = time.ParseInLocation(formWithoutZone, "Jul 9, 2012 at 5:02am", time.Local)
fmt.Println(t)
}

最新更新