PostgreSQL存储time类型与Go语言测试时间匹配问题咨询
解决方案:PostgreSQL time 类型与 Go time.Time 对比问题
问题根源:Go 的 time.Parse("15:04", "11:30") 生成的时间默认日期为 0001-01-01,而 PostgreSQL 的 time without time zone 类型通过 pgx 读取到 time.Time 时,默认会填充 2000-01-01 作为日期部分,两者日期不一致导致直接对比失败。
以下是几种更优的处理方案:
方案1:对比时忽略日期部分
直接编写辅助函数,仅比较时间的时分秒、纳秒及时区信息,无需修改原始时间对象:
func isSameTime(a, b time.Time) bool { return a.Hour() == b.Hour() && a.Minute() == b.Minute() && a.Second() == b.Second() && a.Nanosecond() == b.Nanosecond() && a.Location() == b.Location() } // 使用示例 if isSameTime(sourceTime, sqlTime) { // 时间一致 }
方案2:统一存入时的日期为 PostgreSQL 默认值
在生成待存入的时间时,将日期部分设置为 PostgreSQL 返回的默认日期(2000-01-01),这样存入后读取的时间可直接用 == 对比:
sourceTime, err := time.Parse("15:04", "11:30") if err != nil { // 错误处理 } // 调整日期为PostgreSQL time类型对应的默认日期 sourceTime = time.Date(2000, 1, 1, sourceTime.Hour(), sourceTime.Minute(), sourceTime.Second(), sourceTime.Nanosecond(), sourceTime.Location()) // 存入数据库后,读取的sqlTime与sourceTime直接相等
方案3:使用 pgx 专用的 time 类型
pgx 提供了 pgtype.Time 类型,专门映射 PostgreSQL 的 time without time zone,仅保留时间部分,无冗余日期:
import "github.com/jackc/pgx/v5/pgtype" // 从数据库读取 var startTime pgtype.Time err := pool.QueryRow(ctx, "SELECT start_order FROM orders WHERE id = $1", orderID).Scan(&startTime) if err != nil { // 错误处理 } // 生成待对比的时间并转为pgtype.Time sourceTime, err := time.Parse("15:04", "11:30") if err != nil { // 错误处理 } var sourcePgTime pgtype.Time sourcePgTime.Set(sourceTime) // 直接对比 if startTime == sourcePgTime { // 时间一致 }
内容的提问来源于stack exchange,提问作者Vladimir Chizh
相关产品推荐
相关产品推荐

