doutun1875
2018-11-29 01:55
浏览 296
已采纳

time.Parse错误,我在做什么错?

I'm running into the most bizarre issue regarding datestring parsing in golang using the time package.

The Error:

parsing time "07-20-2018" as "2006-01-02": cannot parse "0-2018" as "2006"

The Code Block:

log.Println(datestring) //07-20-2018
date, err := time.Parse("2006-01-02", datestring)
log.Println(err) //parsing time "07-20-2018" as "2006-01-02": cannot parse "0-2018" as "2006"
log.Println(date) //parsing time "07-20-2018" as "2006-01-02": cannot parse "0-2018" as "2006"

I'm completely at a loss to what this issue is referring to, the string is parsed from the URI in golang with gorilla mux.

datestring, _ := vars["date"] //some/path/{date}, date is 07-20-2018

Any ideas?

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

关于使用时间包在golang中解析日期字符串,我遇到了最奇怪的问题。

错误:

 将解析时间“ 07-20-2018”解析为“ 2006-01-02”:无法解析“ 0  -2018“作为” 2006“ 
   
 
 

代码块:

  log.Println(datestring)//  2018/7/20 
date,err:= time.Parse(“ 2006-01-02”,datestring)
log.Println(err)//将时间“ 07-20-2018”解析为“ 2006-01-02  “:无法将” 0-2018“解析为” 2006“ 
log.Println(date)//将时间” 07-20-2018“解析为” 2006-01-02“:无法将” 0-2018“解析为” 2006  “ 
   
 
 

我完全不知该问题是指什么,该字符串是通过golang中的gorilla mux从URI中解析出来的。

  datestring,_:= vars [“ date”] //一些/路径/ {date},日期为2018年7月20日
   
  
 

有什么想法吗?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dragon012100 2018-11-29 02:11
    已采纳

    It is obvious. You are trying to parse mm-dd-yyyy as yyyy-mm-dd.


    A simple fix:

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
        datestring := "07-20-2018"
        fmt.Println(datestring)
        date, err := time.Parse("01-02-2006", datestring)
        fmt.Println(date, err)
    }
    

    Playground: https://play.golang.org/p/gK7cMAkrP7l

    Output:

    07-20-2018
    2018-07-20 00:00:00 +0000 UTC <nil>
    

    See Go Package time.

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

相关推荐 更多相似问题