dougekui1518
2019-03-23 09:26
浏览 1.2k

如何在postgres中查询timestamptz并与time.Time中的时间进行比较? [重复]

This question already has an answer here:

I'm using Postgres 10 and with a dummy table

CREATE TABLE demo (now timestamptz);

When using jmoiron/sqlx, I can't compare time.Time with timestamptz. The sample code is

db, _ := sqlx.Connect("postgres", dsn)
now, _ := time.Parse(time.RFC3339, "2019-03-22T00:00:00Z")
db.Exec("INSERT INTO demo (now) VALUES ($1)", now)

query := "SELECT timezone('utc', now) as now FROM demo"
type row struct{ Now time.Time }
var rows []row
if err := db.Select(&rows, query); err != nil {
    log.Fatal(err)
}
want := []row{ { Now: now } }
if !reflect.DeepEqual(rows, want) {
    log.Printf("want: %v; got: %v", want, rows)
}

I got results saying they are not equal in the last step

 want: [{0 2019-03-22 00:00:00 +0000 UTC}]
 got: [{0 2019-03-22 00:00:00 +0000 +0000}]

What should I do make reflect.DeepEqual think both are equal?

</div>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongwo8827523 2019-03-23 09:40
    已采纳

    You should not use DeepEqual for time comparison. You should compare times using the time package. You should do:

    now.Equal(rows[0].Now)
    
    点赞 打赏 评论

相关推荐 更多相似问题