为了账号安全,请及时绑定邮箱和手机立即绑定

为什么 go-pg 中的插入时间会改变

为什么 go-pg 中的插入时间会改变

Go
交互式爱情 2022-05-23 15:41:38
我想使用 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-pgreportMessage := &ReportMessage{                    Total:      ii,                    Date:            date                }_, err = p.ormer.Model(reportMessage).Returning("id").Insert()date插入后的值为2020-03-17 17:00:00+00:00:00看起来是因为时区如何在不受时区或其他任何影响的情况下将时间完全插入原始值?
查看完整描述

2 回答

?
料青山看我应如是

TA贡献1772条经验 获得超8个赞

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

reportMessage.Date := date.UTC()


查看完整回答
反对 回复 2022-05-23
?
智慧大石

TA贡献1946条经验 获得超3个赞

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


查看完整回答
反对 回复 2022-05-23
  • 2 回答
  • 0 关注
  • 125 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号