假设我有以下内容:
Postgres 数据库中带有列的表TIMESTAMP
。
数据库时区设置为 UTC 以外的时间。
一些使用CURRENT_TIMESTAMP
or插入时间戳值的 SQL 语句NOW()
正如 Postgres 文档中所述:
CURRENT_TIMESTAMP() 函数返回一个带有时区的 TIMESTAMP,表示事务开始的日期和时间。
因此,以下语句默默地将本地时间戳转换为绝对时间戳:
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
鸿蒙传说
相关分类