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

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

1个答案

1

In GORM, autoCreateTime and autoUpdateTime are convenient features that automatically set the creation and update timestamps for models. By default, these timestamps use the local time zone of the database server. If you want to configure these timestamp fields in a specific time zone, you can implement this through custom callbacks.

Although GORM does not directly support setting the time zone parameter, it can be achieved using Go's standard library to specify time and time zone. The following outlines the steps to configure these fields in a specific time zone (e.g., Tokyo time zone):

  1. Import necessary packages Ensure you have imported the required packages:

    go
    import ( "time" "gorm.io/gorm" )
  2. Define the model Define your model with CreatedAt and UpdatedAt fields:

    go
    type User struct { gorm.Model Name string }
  3. Customize callbacks Customize callbacks during GORM initialization to enforce the use of a specific time zone for timestamp fields:

    go
    func setTimezone(db *gorm.DB) { // Set the desired time zone, e.g., Tokyo time zone 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. Apply the custom callback Apply the custom callback function when initializing the database connection:

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

This way, whenever a User object is created or updated, CreatedAt and UpdatedAt will use the current time in the Tokyo time zone. This example uses Tokyo time zone, but you can set any other time zone by modifying the parameter in LoadLocation.

By using the callback mechanism, you can flexibly control any behavior in GORM, including the handling of timestamp fields. Although this approach requires writing more code, it provides high customization flexibility.

2024年8月12日 17:47 回复

你的答案