我想使用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
看起来是因为时区
如何在不受时区或其他因素影响的情况下将时间准确地插入为原始值?
发布于 2020-03-18 06:16:23
在模型中尝试使用UTC日期:
reportMessage.Date := date.UTC()发布于 2020-04-29 17:44:50
另一种方法是让-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或类似的方法,您可能需要服务器的时间进行正确的配置。
https://stackoverflow.com/questions/60734080
复制相似问题