为什么go pg中的插入时间发生了变化



我想使用go-pg将时间插入数据库,但插入后值会发生变化。

toRound := time.Now()
date := time.Date(toRound.Year(), toRound.Month(), toRound.Day(), 0, 0, 0, 0, toRound.Location())

date的值为2020-03-18 00:00:00 +0700 WIB

并使用go-pg插入

reportMessage := &ReportMessage{
Total:      ii,
Date:            date
}
_, err = p.ormer.Model(reportMessage).Returning("id").Insert()

插入后的date值为2020-03-17 17:00:00+00:00:00

它看起来像是因为时区

如何在不受时区或其他因素影响的情况下将时间准确地作为原始值插入?

尝试在模型中使用UTC日期:

reportMessage.Date := date.UTC()

另一种方法是让go pg ORM自动处理此问题。如果你定义你的模型像:

type ReportMessage struct {
// Your data fields here
CreatedAt time.Time `pg:"default:now()" json:"created_at"`
UpdatedAt time.Time `pg:"default:now()" json:"updated_at`
}

这将告诉go pg/Postgres在插入新记录时使用now()。然后,您可以处理时区和代码中的内容,而数据库将始终以UTC为时间戳。您可能需要使用NTP或类似方法正确配置服务器的时间。

最新更新