英文:
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
你正在将日期放在时间布局的位置。
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.
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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论