【发布时间】: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
【问题讨论】:
-
如果表中的列是没有时区的纯时间戳 - 那么信息已经丢失并且您无法转换它