Setting the default time zone is crucial, especially when dealing with time and date-related data types. By default, GORM uses the database's native time zone setting. To set or change the default time zone in GORM, you can use the following methods:
Method One: Specify Time Zone in Database Connection String
When initializing the database connection, you can specify the time zone in the connection string, so all operations performed through this connection will automatically use the specified time zone. The specific implementation may vary depending on the database type you use (e.g., MySQL, PostgreSQL).
For example, when using MySQL, you can set it as follows:
goimport ( "gorm.io/driver/mysql" "gorm.io/gorm" ) func main() { dsn := "username:password@tcp(host:3306)/dbname?parseTime=true&loc=Asia%2FShanghai" db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{}) if err != nil { panic("failed to connect database") } // The rest of the code for database operations }
In this example, the loc parameter is set to "Asia/Shanghai", indicating that all time values are processed in the Shanghai time zone.
Method Two: Set Time Zone in GORM Configuration
If you prefer to more explicitly control the time zone at the application level, you can set time.Location in the GORM configuration to define the time zone for models. By adding time zone information in the model definition, you can control how time fields are read and written.
goimport ( "gorm.io/gorm" "time" ) type User struct { gorm.Model Name string Birthday time.Time `gorm:"type:datetime;default:CURRENT_TIMESTAMP"` } func main() { loc, _ := time.LoadLocation("Asia/Shanghai") db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{ NowFunc: func() time.Time { return time.Now().In(loc) }, }) if err != nil { panic("failed to connect database") } // Other database operations using db }
In this configuration, by overriding the NowFunc function, GORM will use the specified time zone when handling timestamps (e.g., created and updated times).
Summary
Both methods can effectively set and manage the default time zone in GORM. The choice depends on your specific requirements and preferences. If you need to unify the time zone setting at the database level, choose Method One; if you need more flexible control at the application level, choose Method Two. When handling global applications involving multiple time zones, properly managing the time zone is crucial.