dty47696 2018-11-08 07:58
浏览 90
已采纳

如何使用Go提取postgres时间戳范围?

I have a database calendar with tsrange type from postgres. It allows me to have multiple appointments and time range such as :

["2018-11-08 10:00:00","2018-11-08 10:45:00"]

How do I store this value in a Go variable ?

I tried

var tsrange []string

And when I log tsrange[0] it is empty. What is the proper type for it ?

More code :

rows, err := db.Query("SELECT * FROM appointments")
utils.CheckErr(err)

var id int
var userID int
var tsrange []string

rows.Next()
err = rows.Scan(&id, &userID, &tsrange)

fmt.Println(tsrange[0])

When I replace var tsrange []string with var tsrange string the log is ["2018-11-08 10:00:00","2018-11-08 10:45:00"].

  • 写回答

1条回答 默认 最新

  • doushi7761 2018-11-08 09:00
    关注

    You should be able to retrieve the individual bounds of a range at the sql level.

    // replace tsrange_col with the name of your tsrange column
    rows, err := db.Query("SELECT id, user_id, lower(tsrange_col), upper(tsrange_col) FROM appointments")
    utils.CheckErr(err)
    
    var id int
    var userID int
    var tsrange [2]time.Time
    
    rows.Next()
    err = rows.Scan(&id, &userID, &tsrange[0], &tsrange[1])
    
    fmt.Println(tsrange[0]) // from
    fmt.Println(tsrange[1]) // to
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?