Search code examples
mysqldatetimegogo-gorm

How to set default Timezone on GORM time.Time data type


I am using gorm with mysql as database with go module like this :

  • gorm.io/gorm v1.21.7
  • github.com/go-sql-driver/mysql v1.6.0

My system timezone is +07:00 (Asia/Jakarta), and the mysql timezone is using the system timezone itself.

but something wrong happen when I've struct like this

type Name struct {
    ID         uint64    `gorm:"id;primaryKey;autoIncrement"`
    Name       string    `gorm:"column:name"`
    CreatedAt  time.Time `gorm:"column:created_at"`
    UpdatedAt  time.Time `gorm:"column:updated_at"`
}

on the mysql table created_at and updated_at declared as DATETIME, when I print the CreatedAt and UpdatedAt value, the timezone is +0000 (UTC), when I'm trying to use the Time.In function I got the wrong value, like I'm converting a time from UTC to +07:00, how can I declare to GORM that I'm using +07:00 as default timezone.


Solution

  • When connecting to the MySQL database, ensure you leverage the parseTime and loc parameters as per the docs:

    to scan MySQL DATE and DATETIME values into time.Time variables, which is the logical equivalent in Go to DATE and DATETIME in MySQL. You can do that by changing the internal output type from []byte to time.Time with the DSN parameter parseTime=true. You can set the default time.Time location with the loc DSN parameter.

    to generate a DSN connection strings to set parseTime & loc see i.e.

    loc, _ := time.LoadLocation("Asia/Jakarta") // handle any errors!
    
    c := mysql.Config{
        User:                    "....",
        Passwd:                  "....",
        DBName:                  "....",
        Addr:                    "....:3306",
        Net:                     "tcp",
        ParseTime:               true,
        Loc:                     loc,
    }
    fmt.Println(c.FormatDSN())
    

    https://go.dev/play/p/5yoEbmrPqlZ