How to save time in the database in Go when using

2019-07-26 03:13发布

问题:

I'm currently parsing a time string and saving it to the db (Postgresql):

event.Time, _ := time.Parse("3:04 PM", "9:00 PM")
// value of event.Time now is: 0000-01-01 21:00:00 +0000 UTC
db.Create(&event)

It's giving me this error: pq: R:"DateTimeParseError" S:"ERROR" C:"22008" M:"date/time field value out of range: \"0000-01-01T21:00:00Z\"" F:"datetime.c" L:"3540"

event.Time⁠⁠⁠⁠'s type is time.Time.

I also tried setting event.Time's type to string and using time data type in postgresql:

type Event struct {
  Time string `gorm:"type:time
}

But now I'm getting an error when fetching records in the db:

sql: Scan error on column index 4: unsupported driver -> Scan pair: time.Time -> *string

回答1:

Investigated this issue further. Currently, there's no support in GORM for any Date/Time types except timestamp with time zone

See this part of code from dialect_postgres.go:

case reflect.Struct:
   if _, ok := dataValue.Interface().(time.Time); ok {
      sqlType = "timestamp with time zone"
}

So basically I see two options for you:

Either use varchar(10) in DB, and string in Go, an simply save it as "9:00 PM" (where 10 is some number that suits you)

Or use timestamp with time zone in DB, time.Time in Go, and format your date part as a constant date, 01/01/1970, for example:

time.Parse("2006-01-02 3:04PM", "1970-01-01 9:00PM")

In that case you'll have to omit the date part in your presentation, but if you plan to select by date range, that could work better for you.