如何设置数据库的时区

How to set the timezone of the database

我正在尝试在 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)