Your Question
I got a Postgres database whose timezone is set to CST. And there are some data in DB like this:
Column Type: timestamp (without timezone)
Value: 2022-02-28 10:00:00
I think this should be considered as the time 2022-02-28 10:00:00 CST because the database timezone has been set.
But when I get the data from GORM like this:
2022-02-28 18:00:00 CST
My struct:
Mytime *time.Time `gorm:"column:mytime"`
I also tried to specify the gorm type as timestamp, but it didn't help.
Expected answer
I think it should be returned as 2022-02-28 10:00:00 UTC,
just like other databases (MySQL, SqlServer) which I have tested.
My Suggestion
Although it could remain to be controversial whether it is a bug or not,
Because 2022-02-28 10:00:00 UTC and 2022-02-28 18:00:00 CST is actually the same value.
But I still think 2022-02-28 10:00:00 UTC should be returned.
Because we know there is no zero timezone in time.Time,
Go will parse the nil timezone automatically into UTC.
In this case, the value in the database should be considered as nil timezone rather than zero timezone.
Comment From: devoren
@LawyZheng Have you tried changing session config?
Comment From: LawyZheng
@LawyZheng Have you tried changing session config?
Did you mean the timezone config in the connecting string?
Comment From: devoren
Did you mean the timezone config in the connecting string?
Yeah, when you use gorm.Open, you can pass options (maybe it will help):
db, err := gorm.Open(
postgres.Open(fmt.Sprintf("host=%s port=%s dbname=%s user=%s password=%s sslmode=disable",
config.Host, config.Port, config.DB, config.User, config.Password,
)),
&gorm.Config{
NowFunc: func() time.Time {
return time.Now().UTC()
},
},
)