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

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?

  • 写回答

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.

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

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看