登录
首页 >  Golang >  Go问答

设置数据库的时间区域

来源:stackoverflow

时间:2024-03-04 18:06:25 341浏览 收藏

golang学习网今天将给大家带来《设置数据库的时间区域》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习Golang或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!

问题内容

我正在尝试在 gorm 中设置数据库的时区。 我将数据库时区设置为 utc,在 pgadmin 中我添加了一个带有时区和值 utc 的参数。

一切工作正常,数据以 utc 保存,以 utc 检索,但是当我将新结构保存到数据库时,例如 user,保存后如果验证 user.created_at 不在 utc 时区中,而是在我的本地时区中.

我想让这个工作正常进行,因为我使用创建的 user 创建对正在进行的请求的响应。

更新: 我的代码:

type Customer struct {
    ID          uuid.UUID  `gorm:"type:uuid;primary_key;index;" json:"id"`
    CreatedAt   time.Time  `json:"created_at"`
    UpdatedAt   time.Time  `json:"updated_at"`
    DeletedAt   *time.Time `json:"deleted_at,omitempty"`
 }

解决方案


你可以尝试在gorm中回调。像这样

// updatetimestampforcreatecallback will set `createdat`, `updatedat` when creating
func updatetimestampforcreatecallback(scope *gorm.scope) {
    if !scope.haserror() {
        now := time.now().utc()

        if createdatfield, ok := scope.fieldbyname("createdat"); ok {
            if createdatfield.isblank {
                createdatfield.set(now)
            }
        }

        if updatedatfield, ok := scope.fieldbyname("updatedat"); ok {
            if updatedatfield.isblank {
                updatedatfield.set(now)
            }
        }
    }
}

// updatetimestampforupdatecallback will set `updatedat` when updating
func updatetimestampforupdatecallback(scope *gorm.scope) {
    if _, ok := scope.get("gorm:update_column"); !ok {
        scope.setcolumn("updatedat", time.now().utc())
    }
}

然后在db.callback()中注册

db.Callback().Create().Replace("gorm:update_time_stamp", updateTimeStampForCreateCallback)
db.Callback().Update().Replace("gorm:update_time_stamp", updateTimeStampForUpdateCallback)

到这里,我们也就讲完了《设置数据库的时间区域》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>