使用GORM和Postgresql时如何在Go中节省数据库时间? [英] How to save time in the database in Go when using GORM and Postgresql?
问题描述
我当前正在解析时间字符串并将其保存到数据库(PostgreSQL)中:
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)
这给了我这个错误: pq:R:"DateTimeParseError" S:"ERROR" C:"22008" M:日期/时间字段值超出范围:\" 0000-01-01T21:00:00Z \" F:"datetime.c" L:"3540"
event.Time的类型为
time.Time
.
我还尝试将 event.Time
的类型设置为字符串,并在postgresql中使用时间数据类型:
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
推荐答案
进一步研究了此问题.目前,GORM中不支持任何日期/时间类型,但带有时区的 timestamp
Investigated this issue further. Currently, there's no support in GORM for any Date/Time types except timestamp with time zone
请参见 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:
在DB中使用 varchar(10)
,在Go中使用 string
,只需将其另存为"9:00 PM"(其中10是一些合适的数字即可)您)
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)
或者在DB中使用带有时区的 timestamp
,在Go中使用 time.Time
,并将日期部分格式化为恒定日期,例如01/01/1970.:
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.
这篇关于使用GORM和Postgresql时如何在Go中节省数据库时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!