乐闻世界logo
搜索文章和话题

In GORM, how to configure autoCreateTime and autoUpdateTime in specific timezone?

1 个月前提问
1 个月前修改
浏览次数9

1个答案

1

在GORM中,autoCreateTimeautoUpdateTime 是非常方便的功能,可以自动地为模型设置创建时间和更新时间。默认情况下,这些时间会使用数据库服务器的本地时区。如果想要在特定时区下配置这两个时间字段,可以通过自定义回调的方式来实现。

GORM本身并没有直接支持设置时区的参数,但可以通过Go语言的标准库来指定时间和时区。以下是一个如何实现在特定时区(例如东京时区)中配置这两个字段的步骤:

  1. 导入必要的包 确保你已经导入了GORM和Go的时间包:

    go
    import ( "time" "gorm.io/gorm" )
  2. 定义模型 在你的模型中定义CreatedAtUpdatedAt字段:

    go
    type User struct { gorm.Model Name string }
  3. 自定义回调 在GORM初始化时,可以自定义CreateUpdate的回调,来强制使用特定时区的时间:

    go
    func setTimezone(db *gorm.DB) { // 设置你希望使用的时区,例如东京时区 location, err := time.LoadLocation("Asia/Tokyo") if err != nil { panic(err) } db.Callback().Create().Replace("gorm:update_time_stamp", func(db *gorm.DB) { now := time.Now().In(location) if db.Statement.Schema != nil { if field, ok := db.Statement.Schema.FieldsByName["CreatedAt"]; ok { _ = field.Set(db.Statement.ReflectValue, now) } if field, ok := db.Statement.Schema.FieldsByName["UpdatedAt"]; ok { _ = field.Set(db.Statement.ReflectValue, now) } } }) db.Callback().Update().Replace("gorm:update_time_stamp", func(db *gorm.DB) { now := time.Now().In(location) if db.Statement.Schema != nil { if field, ok := db.Statement.Schema.FieldsByName["UpdatedAt"]; ok { _ = field.Set(db.Statement.ReflectValue, now) } } }) }
  4. 应用自定义回调 在初始化数据库连接时应用这个自定义回调的函数:

    go
    db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) if err != nil { panic("failed to connect database") } setTimezone(db)

这样,每次创建或更新User对象时,CreatedAtUpdatedAt将会使用东京时区的当前时间。这个例子使用了东京时区,但你可以通过修改LoadLocation中的参数来设置任何其他的时区。

通过使用回调机制,我们可以非常灵活地控制在GORM中的任何行为,包括时间字段的处理。这种方法虽然需要写更多的代码,但它提供了极高的自定义灵活性。

2024年8月12日 17:47 回复

你的答案