将类似于”2021-05-06 00:00:00 +0530 IST”的字符串转换为time.Time值。

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

Converting string like "2021-05-06 00:00:00 +0530 IST" to time.Time value

问题

我有一个字符串 2021-05-06 00:00:00 +0530 IST,我需要将其转换为 golang 中的 time.Time 值。我知道如何做,但我不知道用于解析这种类型字符串的布局应该是什么。

time, err := time.ParseInLocation("2021-05-06 00:00:00 +0530 IST", addedOn, loc)

这给我带来了错误,如 "error":"parsing time \"2021-05-06 00:00:00 +0530 IST\" as \"2021-05-06 00:00:00 +0530 IST\": cannot parse \"-05-06 00:00:00 +0530 IST\" as \"1\""

那么,这种字符串的正确布局应该是什么?

英文:

I have the following string 2021-05-06 00:00:00 +0530 IST that I need to convert to a time.Time value in golang. I know how to do it but I don't know what the layout should be to parse these type of strings.

time, err := time.ParseInLocation("2021-05-06 00:00:00 +0530 IST", addedOn, loc)

And this is giving me errors like "error":"parsing time \"2021-05-06 00:00:00 +0530 IST\" as \"2021-05-06 00:00:00 +0530 IST\": cannot parse \"-05-06 00:00:00 +0530 IST\" as \"1\""

So, what should be the correct layout for such strings?

答案1

得分: 3

你正在将日期放在时间布局的位置。

请参阅time#ParseInLocation

func ParseInLocation(layout, value string, loc *Location) (Time, error)

例如:

loc, _ := time.LoadLocation("Europe/Berlin")

// 这将在Europe/Berlin时区中查找名称为CEST的时区。
const longForm = "Jan 2, 2006 at 3:04pm (MST)"
t, _ := time.ParseInLocation(longForm, "Jul 9, 2012 at 5:02am (CEST)", loc)
fmt.Println(t)

在你的情况下:

t , _ := time.ParseInLocation("2006-01-02 15:04:05 -0700 MST", "2021-05-06 00:00:00 +0530 IST", loc)

请参阅playground示例(以及其他ParseInLocation示例

英文:

You are putting the date in place of the time layout.

See time#ParseInLocation

func ParseInLocation(layout, value string, loc *Location) (Time, error)

For instance:

loc, _ := time.LoadLocation("Europe/Berlin")

// This will look for the name CEST in the Europe/Berlin time zone.
const longForm = "Jan 2, 2006 at 3:04pm (MST)"
t, _ := time.ParseInLocation(longForm, "Jul 9, 2012 at 5:02am (CEST)", loc)
fmt.Println(t)

In your case:

t , _ := time.ParseInLocation("2006-01-02 15:04:05 -0700 MST", "2021-05-06 00:00:00 +0530 IST", loc)

See playground example (and other ParseInLocation examples here)

答案2

得分: 1

布局 👇🏻

"2006-01-02 15:04:05 -0700 MST"

请参考文档示例

<kbd>PLAYGROUND</kbd>

英文:

Layout 👇🏻

&quot;2006-01-02 15:04:05 -0700 MST&quot;

Look at docs and examples

<kbd>PLAYGROUND</kbd>

huangapple
  • 本文由 发表于 2021年11月8日 14:20:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/69879312.html
匿名

发表评论

匿名网友

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

确定