Joh*_*enn 3 postgresql go go-gorm
我目前正在解析时间字符串并将其保存到数据库(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)
Run Code Online (Sandbox Code Playgroud)
它给了我这个错误: 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.Time的类型设置为字符串并在 postgresql 中使用时间数据类型:
type Event struct {
Time string `gorm:"type:time
}
Run Code Online (Sandbox Code Playgroud)
但是现在在数据库中获取记录时出现错误:
sql: Scan error on column index 4: unsupported driver -> Scan pair: time.Time -> *string
Run Code Online (Sandbox Code Playgroud)
进一步调查了这个问题。目前,GORM 不支持任何日期/时间类型,除了timestamp with time zone
从dialect_postgres.go 中查看这部分代码:
case reflect.Struct:
if _, ok := dataValue.Interface().(time.Time); ok {
sqlType = "timestamp with time zone"
}
Run Code Online (Sandbox Code Playgroud)
所以基本上我看到了两种选择:
要么varchar(10)在 DB 中使用,要么string在 Go 中使用,只需将其保存为“9:00 PM”(其中 10 是适合您的某个数字)
或者timestamp with time zone在 DBtime.Time中使用 Go,并将您的日期部分格式化为一个常量日期,01/01/1970,例如:
time.Parse("2006-01-02 3:04PM", "1970-01-01 9:00PM")
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您将不得不在演示文稿中省略日期部分,但如果您打算按日期范围进行选择,这可能更适合您。
| 归档时间: |
|
| 查看次数: |
17522 次 |
| 最近记录: |