我正在尝试在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)
关于go - 如何设置数据库的时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60675912/