dongruolin5324 2016-08-03 20:41
浏览 161
已采纳

如何从Golang中的字符串解析日期以插入Postgres?

So I'm trying to parse a time from a string and then insert that time into Postgres.

I have this so far-

layout := "2006-01-02T15:04:05.000Z"
updatedAt, _ := time.Parse("2016-06-10")
fmt.Println(updatedAt)

but this outputs

0001-01-01 00:00:00 +0000 UTC.

I'm also not sure how to then use this to query in postgres (what format should the time have)?

  • 写回答

1条回答 默认 最新

  • dongye6377 2016-08-04 00:58
    关注

    To parse time in your example you'll need correct layout passed to time.Parse:

    layout := "2006-01-02"
    updatedAt, _ := time.Parse(layout, "2016-06-10")
    fmt.Println(updatedAt)
    

    Outputs:

    $ go run time.go
    2016-06-10 00:00:00 +0000 UTC
    

    To insert time you have after parsing it you'll just need to pass time.Time object to db.Exec. For example:

    db.Exec("INSERT INTO tablename VALUES (time_column) (($1));", time.Now())

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?