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())

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

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料