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"
)