在 Golang 中解析 RFC822Z 格式的日期,但不包含前导零。

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

Golang parsing date in RFC822Z format without leading zero

问题

我有一个日期字符串,我无法控制,我想要将其解析为日期。

该格式最接近RFC822Z。

RFC822Z = "02 Jan 06 15:04 -0700"

参考链接:https://yourbasic.org/golang/format-parse-string-time-date-example/

然而,它没有前导零。

例如:"5 Dec 2022 20:15:21 +0000"

我在其他帖子中看到的方法是手动编写一个格式。

parseTime, timeParseError = time.Parse("2 Jan 2006 15:04:21 -0700", stringDate)

然而,当我尝试这样做时,我收到一个警告:

parsing time "2 Jan 2006 15:04:21 -0700" as "2 Jan 2006 15:04:21 -0700": cannot parse " -0700" as "1" (SA1002)

尽管有警告,运行它仍然无法解析,这并不奇怪。

英文:

I have a date string I can't control that I'm trying to parse into a Date.

The format most closely resembles RFC822Z.

RFC822Z = "02 Jan 06 15:04 -0700"

Reference: https://yourbasic.org/golang/format-parse-string-time-date-example/

However, it does not have the leading zero.

Example: "5 Dec 2022 20:15:21 +0000"

The way I saw in other posts, is to write a manual format.

parseTime, timeParseError = time.Parse("2 Jan 2006 15:04:21 -0700", stringDate)

However, when I try that, I get a warning:

parsing time "2 Jan 2006 15:04:21 -0700" as "2 Jan 2006 15:04:21 -0700": cannot parse " -0700" as "1" (SA1002)

Running it despite the warning fails to part, unsurprisingly.

答案1

得分: 1

你的时间格式不匹配-在你的示例中,你使用了"5 Dec 2022",但你使用的是"2 Jan 06",而在你的参考格式中,你使用的是"15:04:21",但应该是"15:04:05"。

你的参考格式应该是2 Jan 2006 15:04:05 -0700,而不是2 Jan 06 15:04:21 -0700

https://go.dev/play/p/Shc381WgB6_7

英文:

Your time format doesn't match - in your example you have "5 Dec 2022", but you are using "2 Jan 06", and in your reference format you hvae "15:04:21" but it should be "15:04:05".

Your reference format should be 2 Jan 2006 15:04:05 -0700 not 2 Jan 06 15:04:21 -0700

https://go.dev/play/p/Shc381WgB6_7

huangapple
  • 本文由 发表于 2022年12月6日 05:14:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/74694463.html
匿名

发表评论

匿名网友

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

确定