Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang inserting time.Now into database being shifted to UTC

Tags:

go

go-gorm

I am trying to insert a time.Now() field into the database, but what keeps happening is the time is shifted forward to UTC. I understand the idea is to always to that then convert to local time when presenting to the user. Problem is I have inherited this system and it is currently far to ingrained to be easily changed.

Any tips? I saw that you can set the loc in the DSN but it does not explain what to change it to nor its actual effect, so I would appreciate information there.

Edit: Some information, it is MySQL DB,using go-mysql 1.1 and go 1.6.3. The data is being inserted into a DATETIME field.

The data is incorrect at the insert. GORM Debug shows one time and MySQL query logger shows it shifted forward.

I have found that the issue is that the go-mysql driver automatically shifts times to be UTC, and this can be altered using the loc parameter in the DSN. This however also changes how the time is returned.

To resolve this add loc=Local to your DSN.

like image 875
Fireynis Avatar asked Jul 19 '16 19:07

Fireynis


1 Answers

This is the way I use to always store local time. Works fine even if your VPS is located on another timezone country:

db, err = gorm.Open("mysql", "root:@tcp(localhost:3306)/mydatabase?charset=utf8&parseTime=True&loc=America%2FSao_Paulo")
like image 167
Gilmar Palega Avatar answered Sep 22 '22 06:09

Gilmar Palega