Search code examples
postgresqlgosqlx

How to query timestamptz in postgres and compare with time.Time in go?


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?


Solution

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

    now.Equal(rows[0].Now)