英文:
Hour out of range on time.parse in golang
问题
我正在尝试在Go语言中解析一个日期时间字符串。我将确切的字符串作为格式传递,并得到一个解析时间错误:"01/31/2000 12:59 AM":小时超出范围。
我从输入中获取该字符串。如何使其工作?
以下是代码(https://play.golang.org/p/Kg9KfFpU2z):
func main() {
layout := "01/31/2000 12:59 AM"
if t, err := time.Parse(layout, "01/31/2000 12:59 AM"); err == nil {
fmt.Println("Time decoded:", t)
} else {
fmt.Println("Failed to decode time:", err)
}
}
英文:
I am trying to parse a date time string in go. I pass the exact string as the format and get and error parsing time "01/31/2000 12:59 AM": hour out of range.
I am getting that string from an input. How can I make this work?
Here is the code (https://play.golang.org/p/Kg9KfFpU2z)
func main() {
layout := "01/31/2000 12:59 AM"
if t, err := time.Parse(layout, "01/31/2000 12:59 AM"); err == nil {
fmt.Println("Time decoded:", t)
} else {
fmt.Println("Failed to decode time:", err)
}
}
答案1
得分: 3
根据你分享的代码,你应该将布局更改为01/02/2006 03:04 AM
来修复它:
注意:
如果你使用的是24小时制,你应该将布局中的小时部分改为15
而不是03
,并且去掉AM
部分,例如01/02/2006 15:04
package main
import (
"fmt"
"time"
)
func main() {
layout := "01/02/2006 03:04 AM"
if t, err := time.Parse(layout, "01/31/2000 12:59 AM"); err == nil {
fmt.Println("Time decoded:", t)
} else {
fmt.Println("Failed to decode time:", err)
}
}
这里有一篇很好的文章,可以帮助你了解不同的布局。
英文:
Based on your shared code, you should change the layout to 01/02/2006 03:04 AM
to fix it:
Note:
If you have 24 hours format, you should change the hour part in layout to 15 instead of 03
and also to get rid of AM
part e.g. 01/02/2006 15:04
package main
import (
"fmt"
"time"
)
func main() {
layout := "01/02/2006 03:04 AM"
if t, err := time.Parse(layout, "01/31/2000 12:59 AM"); err == nil {
fmt.Println("Time decoded:", t)
} else {
fmt.Println("Failed to decode time:", err)
}
}
Here is a good article that would help you to understand different layouts.
答案2
得分: 0
你的格式需要使用非常特定的日期和时间格式,请参考文档:
https://golang.org/pkg/time/#example_Parse
Parse函数解析一个格式化的字符串并返回它表示的时间值。布局(layout)定义了格式,它展示了参考时间(reference time)的格式,参考时间被定义为:
Mon Jan 2 15:04:05 -0700 MST 2006
所以你需要使用 https://play.golang.org/p/c_Xc_R2OHb 这个链接。
英文:
Your format needs to use a very specific date and time, see the docs:
https://golang.org/pkg/time/#example_Parse
> 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
So you need https://play.golang.org/p/c_Xc_R2OHb
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论