Go 中 time.Parse 报错:year/month/day hour/minute/second out of range 时间格式化为什么是 2006-01-02 15:04:05?
生活随笔
收集整理的這篇文章主要介紹了
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 zoneRFC850 = "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 zoneRFC3339 = "2006-01-02T15:04:05Z07:00"RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"Kitchen = "3:04PM"
)
總結
以上是生活随笔為你收集整理的Go 中 time.Parse 报错:year/month/day hour/minute/second out of range 时间格式化为什么是 2006-01-02 15:04:05?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 久旱逢甘露作者是谁啊?
- 下一篇: Go 学习笔记(36)— 基于Go方法的