0

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

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

的值date2020-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

看起来是因为时区

如何在不受时区或其他任何影响的情况下将时间完全插入原始值?

4

2 回答 2

1

另一种方法是让 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 或类似方法正确配置服务器的时间。

于 2020-04-29T17:44:50.693 回答
1

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

reportMessage.Date := date.UTC()
于 2020-03-18T06:16:23.593 回答