Go 语言 time.Parse 报错:month out of range

1. 问题现象

在使用 Go 语言的 time.Parse 解析时间时遇到以下错误:

func main() {
	timeParse, err := time.Parse("2006-11-02 15:04:05", "2020-05-22 10:25:30")
	if err != nil {
		fmt.Println("time parse failed: ", err)
	}
	fmt.Printf("timeParse is %v, type is %T", timeParse, timeParse)
}

报错:

time parse failed:  parsing time "2020-05-22 10:25:30": month out of range
timeParse is 0001-01-01 00:00:00 +0000 UTC, type is time.Time

2. 问题分析

查看源码发现有以下描述

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.

layout 这个参数是被定义为 Mon Jan 2 15:04:05 -0700 MST 2006

3. 问题解决

我们修改 “2006-11-02 15:04:05” 为 “2006-01-02 15:04:05”

func main() {
	timeParse, err := time.Parse("2006-01-02 15:04:05", "2020-05-22 10:25:30")
	if err != nil {
		fmt.Println("time parse failed: ", err)
	}
	fmt.Printf("timeParse is %v, type is %T", timeParse, timeParse)
	// timeParse is 2020-05-22 10:25:30 +0000 UTC, type is time.Time
}

执行结果:

timeParse is 2020-05-22 10:25:30 +0000 UTC, type is time.Time
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 书香水墨 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读