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

Viewed 68

The created_at and updated_at fields of my MariaDB database are previously filled with dates of my specific timezone (Europe/Paris).

I have now integrated GORM (v1.23.8), however, when using autoCreateTime and autoUpdateTime in my GORM model, the dates are always written in UTC. How can I configure GORM, so that the autoCreateTime and autoUpdateTime dates are written in a different timezone than UTC.

I have tried to add the Loc and ParseTime params to the MariaDB connection string, but that didn't fix the issue.

2 Answers

GORM v1.23.8 specifies the autoCreateTime and autoUpdateTime field config to contain a UNIX timestamp, which is implicitly UTC timezone, therefor it seems impossible to change the timezone for autoCreateTime and autoUpdateTime.

The workaround would be to not specify your created_at and updated_at fields with autoCreateTime and autoUpdateTime, but as normal date fields and set the dates manually in your code.

While there are many reasons why you should store your dates in your database as UTC (e.g. many frontend frameworks expect dates in UTC, and will localize them themselves), since I'm working on a legacy system which already stored the database dates in the local time zone, here is a solution that I found works for me:

gormDB, err := gorm.Open(mysql.Open(fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", userName, password, hostName, port, dbname)), &gorm.Config{
    NowFunc: func() time.Time {

        currentTime := time.Now()
        _, offset := currentTime.Zone()
        mysqlTime := currentTime.Add(time.Second * time.Duration(offset))
        return mysqlTime
    },
})
Related