Go time.Parse() 出现 “月份超出范围” 错误。

huangapple go评论75阅读模式
英文:

Go time.Parse() getting "month out of range" error

问题

我是你的中文翻译助手,以下是你要翻译的内容:

我刚开始学习Go语言,正在创建一个小的控制台脚本。你可以在这里查看我的代码:

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

我看到了一个相关的问题,但是我不明白为什么会出错。

运行我的代码后,我得到了以下错误信息:

parsing time "2016-12-25 22:40:00": month out of range
0001-01-01 00:00:00 +0000 UTC

你有什么想法,我做错了什么吗?

谢谢。

英文:

I'm new to Go and I was creating a little console script. 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

答案1

得分: 30

你在time.Parselayout参数中使用了错误的参考时间,应该是Jan 2, 2006 at 3:04pm (MST)

将你的begin行更改为以下内容,它将正常工作:

begin, err := time.Parse("2006-01-02 15:04:05", "2016-12-25 "+string(start)+":00")

func Parse

英文:

You're using the wrong reference time in the layout parameter of time.Parse which should be Jan 2, 2006 at 3:04pm (MST)

Change your begin line to the following and it will work:

begin, err := time.Parse("2006-01-02 15:04:05", "2016-12-25 "+string(start)+":00")

func Parse

答案2

得分: 0

为了避免记住特殊日期,我通常会将逻辑封装在一个函数中:

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)
}
英文:

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

huangapple
  • 本文由 发表于 2016年11月4日 22:55:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/40425699.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定