Go 中 time.Parse 报错:year/month/day hour/minute/second out of range 时间格式化为什么是 2006-01-02 15:04:05?

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

官方定义的时间格式常量:

const (
    ANSIC       = "Mon Jan _2 15:04:05 2006"
    UnixDate    = "Mon Jan _2 15:04:05 MST 2006"
    RubyDate    = "Mon Jan 02 15:04:05 -0700 2006"
    RFC822      = "02 Jan 06 15:04 MST"
    RFC822Z     = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone
    RFC850      = "Monday, 02-Jan-06 15:04:05 MST"
    RFC1123     = "Mon, 02 Jan 2006 15:04:05 MST"
    RFC1123Z    = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone
    RFC3339     = "2006-01-02T15:04:05Z07:00"
    RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
    Kitchen     = "3:04PM"
)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wohu007

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值