在Go语言的Parse()函数中,为什么time.ANSIC布局无法工作?

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

In Parse() function, why the time.ANSIC layout didn't work in Go?

问题

我目前正在学习时间库,我不确定为什么在布局部分使用 time.ANSIC 没有按照我期望的方式工作。

在 Parse() 函数中,有一个语法 func Parse(layout, value string),根据我的理解,我可以在布局部分使用 time.UnixDate、ANSIC、RFC3339 等。

当我像下面这样编码时:

const layout = "Jan 2, 2006 at 3:04pm (MST)"
sm, _ := time.Parse(layout, "Feb 4, 2014 at 6:05pm (PST)")
fmt.Println(sm)

它也能正常工作,我得到了 2014-02-04 18:05:00 +0000 PST。

然而,当我在布局部分添加 time.ANSIC 时:

tm, _ := time.Parse(time.ANSIC, "Feb 4, 2014 at 6:05pm (PST)")
fmt.Println(tm)

我得到的是 0001-01-01 00:00:00 +0000 UTC。

我不确定为什么我得不到任何时间。非常感谢你的帮助!

英文:

I am currently studying time library and I am not sure why the time.ANSIC at layout part didn't work what I expected.
In Parse() function there is a syntax func Parse (layout, value string) and based on my understanding I can use in layout part like time.UnixDate, ANSIC, RFC3339 etc.

When I code like below

const layout = "Jan 2, 2006 at 3:04pm (MST)"
	sm, _ := time.Parse(layout, "Feb 4, 2014 at 6:05pm (PST)")
	fmt.Println(sm)

It works as well and I got 2014-02-04 18:05:00 +0000 PST.

However, when I add time.ANSIC at layout part

tm, _ := time.Parse(time.ANSIC, "Feb 4, 2014 at 6:05pm (PST)")
	fmt.Println(tm)

I got 0001-01-01 00:00:00 +0000 UTC.

I am not sure why do I get any time. I really appreciate your help!

答案1

得分: 1

在标准库的任何方法中,丢弃返回的错误并不符合Go语言的习惯。在处理返回值之前,始终要先检查这些错误。

如果你注意到了来自解析函数的错误,你会发现time.ANSIC的格式与你尝试解析的日期字符串不兼容。

> 将时间"Feb 4, 2014 at 6:05pm (PST)"解析为"Mon Jan _2 15:04:05 2006"时出错:无法解析"Feb 4, 2014 at 6:05pm (PST)"为"Mon"。

参考链接:https://pkg.go.dev/time#Parse

> 第二个参数必须能够使用作为第一个参数提供的格式字符串(布局)进行解析。

链接:https://go.dev/play/p/jU-EvL5W3Hp

英文:

It is not idiomatic Go to discard errors returned from any of the methods in standard library. Always check them before processing your returned value.

If you had noticed the error from your parse function, you would see that the layout for time.ANSIC is not compatible with the date string that you are trying to parse

> parsing time "Feb 4, 2014 at 6:05pm (PST)" as "Mon Jan _2 15:04:05 2006": cannot parse "Feb 4, 2014 at 6:05pm (PST)" as "Mon"

From https://pkg.go.dev/time#Parse

> The second argument must be parseable using the format string (layout) provided as the first argument.

https://go.dev/play/p/jU-EvL5W3Hp

huangapple
  • 本文由 发表于 2022年2月11日 14:48:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/71076122.html
匿名

发表评论

匿名网友

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

确定