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):
-
Import necessary packages Ensure you have imported the required packages:
goimport ( "time" "gorm.io/gorm" ) -
Define the model Define your model with
CreatedAtandUpdatedAtfields:gotype User struct { gorm.Model Name string } -
Customize callbacks Customize callbacks during GORM initialization to enforce the use of a specific time zone for timestamp fields:
gofunc 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) } } }) } -
Apply the custom callback Apply the custom callback function when initializing the database connection:
godb, 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.