【问题标题】:How to add time zone information to existing time.Time如何将时区信息添加到现有 time.Time
【发布时间】:2020-02-28 00:06:20
【问题描述】:

假设我有以下内容:

  • Postgres 数据库中带有TIMESTAMP 列的表。
  • 数据库时区设置为 UTC 以外的时间。
  • 一些使用CURRENT_TIMESTAMP 或NOW() 插入时间戳值的SQL 语句

如 Postgres 文档中所述:

CURRENT_TIMESTAMP() 函数返回一个 TIMESTAMP WITH TIME ZONE,表示事务开始的日期和时间。

因此,以下语句将本地时间戳静默转换为绝对时间戳:

INSERT INTO foo (id, timestamp_column) VALUES (0, CURRENT_TIMESTAMP);

假设 Go 程序将此数据读入 time.Time 对象,该对象将有一个空的 Location:

fmt.Println(timeFromDb.Location().String() == "") // true

解释为 UTC。此时我确实知道 Go 时间 timeFromDb 实际上不是 UTC,并且我也知道数据库时区设置是什么。

如何在这个时间对象中设置正确的时区?在实践中:

// before
fmt.Println(timeFromDb)            // 2009-11-10 10:00:00
fmt.Println(timeFromDb.Location()) // <empty>
fmt.Println(timeFromDb.UTC())      // 2009-11-10 10:00:00

// magic?

// after
fmt.Println(timeFromDb)            // 2009-11-10 10:00:00
fmt.Println(timeFromDb.Location()) // America/Vancouver
fmt.Println(timeFromDb.UTC())      // 2009-11-10 18:00:00

【问题讨论】:

  • 如果表中的列是没有时区的纯时间戳 - 那么信息已经丢失并且您无法转换它

标签: go time timezone


【解决方案1】:

你可以重新解释它:

loc,_:=time.LoadLocation("America/Vancouver")
t2:=timeFromDb.In(loc)
_,off:=t2.Zone()
theTime:=t2.Add(-time.Duration(off)*time.Second)

你也可以做一些字符串操作,但我怀疑这样会更快。

【讨论】:

  • 请记住,虽然这可能适用于大多数值,但在转换(DST 的开始/停止或标准时间的变化)附近可能会出现一些错误。换句话说,该 UTC 值的偏移量可能与该本地时间的偏移量不同。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-19
  • 1970-01-01
  • 2019-09-06
  • 2021-04-04
  • 1970-01-01
  • 2010-11-16
  • 1970-01-01
相关资源
最近更新 更多