小编典典

使用GORM和Postgresql时如何在Go中节省数据库时间?

go

我目前正在解析时间字符串并将其保存到数据库(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)

这给了我这个错误: 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⁠⁠⁠⁠的类型是time.Time

我也尝试将event.Timepostgresql的类型设置为string并使用time数据类型:

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

但是现在在获取数据库中的记录时出现错误:

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

阅读 531

收藏
2020-07-02

共1个答案

小编典典

对此问题进行了进一步调查。当前,GORM中不支持任何日期/时间类型,除了timestamp with time zone

请参阅Dialect_postgres.go的这部分代码:

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

因此,基本上我可以为您提供两个选择:

无论是varchar(10)在DB中还是string在Go中,只需将其保存为“ 9:00 PM”(其中10是一些适合您的数字)

或者在Go中使用timestamp with time zoneDB,time.Time并将日期部分格式化为常数日期01/01/1970,例如:

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

在这种情况下,您必须在演示文稿中省略日期部分,但是如果您打算按日期范围进行选择,那可能会更好。

2020-07-02