[英]Go time.Parse() getting “month out of range” error
I'm new to Go and I was creating a little console script.我是 Go 的新手,我正在创建一个小的控制台脚本。 You can check my code here:
你可以在这里查看我的代码:
package main
import (
"bufio"
"fmt"
"os"
"time"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Println("Calculate")
fmt.Print("Hours and minutes: ")
start, _, _ := reader.ReadLine()
begin, err := time.Parse("2016-12-25 00:00:00", "2016-12-25 "+string(start)+":00")
if err != nil {
fmt.Println(err)
}
fmt.Println(begin)
}
I've seen a related question but I couldn't understand why.我看过一个相关的问题,但我不明白为什么。
This is the error I'm getting after running my code:这是我运行我的代码后得到的错误:
parsing time "2016-12-25 22:40:00": month out of range
0001-01-01 00:00:00 +0000 UTC
Any ideas on what am I doing wrong?关于我做错了什么的任何想法?
Thanks谢谢
You're using the wrong reference time in the layout
parameter of time.Parse
which should be Jan 2, 2006 at 3:04pm (MST)
您在
time.Parse
的layout
参数中使用了错误的参考时间,应该是Jan 2, 2006 at 3:04pm (MST)
Change your begin
line to the following and it will work:将您的
begin
行更改为以下内容,它将起作用:
begin, err := time.Parse("2006-01-02 15:04:05", "2016-12-25 "+string(start)+":00")
To avoid having to remember the special date, I usually wrap the logic in a function:为了避免记住特殊日期,我通常将逻辑包装在一个函数中:
package main
import (
"fmt"
"time"
)
func parseDate(value string) (time.Time, error) {
layout := time.RFC3339[:len(value)]
return time.Parse(layout, value)
}
func main() {
start := "15:04"
d, e := parseDate("2016-12-25T" + start)
if e != nil {
panic(e)
}
fmt.Println(d)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.