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

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\""

这样的错误

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

布局

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

看看docs and examples

PLAYGROUND

您正在用日期代替时间布局。

time#ParseInLocation

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

例如:

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)

你的情况:

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

playground example (and other ParseInLocation examples here)