dsshsta97935
2018-09-22 19:04
浏览 674

将mysql datetime解析为golang时间

I have MySQL datetime in my table in the MySQL standard format like

"2018-09-19 18:26:32.000000"

and when I try converting it ti golang time using time.parse() function, I get the error that

parsing time "2018-09-19 18:26:32.000000": month out of range

I tried searching online and the format seems to be allowed and commonly used by many to successfully parse.

Can anyone help me with what I am missing? Below is the code snippet that I am using.

import (
    "fmt"
    "time"
)

layout := "2018-09-19 18:26:32.000000"
fmt.Println(val)
// prints 2018-09-19 18:26:32.000000
t, err := time.Parse(layout, val)
fmt.Println(fmt.Println(t.Unix()))
// prints -62135596800 
fmt.Println(err)
// prints parsing time "2018-09-19 18:26:32.000000": month out of range

图片转代码服务由CSDN问答提供 功能建议

我的表中以MySQL标准格式(如

“ 2018-09-19 18:26:32.000000”

,当我尝试使用 time.parse将其转换为golang时间时 ()函数,出现以下错误

解析时间“ 2018-09-19 18:26:32.000000”:月超出范围

我尝试在线搜索,这种格式似乎已被允许并被许多人成功使用。

有人可以帮我吗? 与我所缺少的? 下面是我正在使用的代码段。

  import(
“ fmt” 
“ time” 
)
 
layout:=“ 2018-09-  19 18:26:32.000000“ 
fmt.Println(val)
 //打印2018-09-19 18:26:32.000000 
t,err:= time.Parse(layout,val)
fmt.Println(fmt。  Println(t.Unix()))
 //打印-62135596800 
fmt.Println(err)
 //打印解析时间“ 2018-09-19 18:26:32.000000”:超出范围的月份
 <  / code>  
 
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duannao1920 2018-09-22 19:20
    已采纳

    Your layout is wrong, it should be "2006-01-02 15:04:05.000000". The documentation states:

    Parse parses a formatted string and returns the time value it represents. The layout defines the format by showing how the reference time, defined to be

    Mon Jan 2 15:04:05 -0700 MST 2006

    would be interpreted if it were the value; it serves as an example of the input format. The same interpretation will then be made to the input string.

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
    
        val := "2018-09-19 18:26:32.000000"
        layout := "2006-01-02 15:04:05.000000"
        t, _ := time.Parse(layout, val)
        fmt.Println(t.Unix()) // prints 1537381592
    }
    

    Outputs

    1537381592
    

    Try it here

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题