【问题标题】:How to parse time using a specific timezone如何使用特定时区解析时间
【发布时间】:2021-10-21 11:21:55
【问题描述】:

我要从字符串中获取时间结构。我正在使用函数time.ParseTime() 和布局"2006-01-02 15:04"

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

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

【问题讨论】:

标签: go time timezone


【解决方案1】:

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

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

【讨论】:

  • 不确定 CEST 等缩写是否在所有系统上给出正确的 UTC 偏移量。你也可以set a specific location
猜你喜欢
  • 2012-09-28
  • 1970-01-01
  • 2023-03-06
  • 2011-07-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-29
  • 2017-09-10
  • 1970-01-01
相关资源
最近更新 更多