【问题标题】:Converting string like "2021-05-06 00:00:00 +0530 IST" to time.Time value将“2021-05-06 00:00:00 +0530 IST”之类的字符串转换为 time.Time 值
【发布时间】:2021-12-21 01:08:19
【问题描述】:

我有以下字符串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\""这样的错误

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

【问题讨论】:

    标签: datetime go time


    【解决方案1】:

    布局 ??

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

    看看docsexamples

    PLAYGROUND

    【讨论】:

    • 在您的游乐场示例中,time.UTC 作为位置有什么作用?
    • ParseInLocation is like Parse but differs in two important ways. First, in the absence of time zone information, Parse interprets a time as UTC; ParseInLocation interprets the time as in the given location. Second, when given a zone offset or abbreviation, Parse tries to match it against the Local location; ParseInLocation uses the given location. ??因为我们使用MST (start),time .UTC 被忽略了。
    • "因为我们使用 MST(开始),time.UTC 被忽略了。" 好的,谢谢,我只是发现这种不直观,我希望像转换到 UTC,但这可能是我对其他语言有偏见;-)
    【解决方案2】:

    您将日期替换为时间布局。

    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(和其他ParseInLocation examples here

    【讨论】:

      猜你喜欢
      • 2012-06-21
      • 1970-01-01
      • 2014-04-24
      • 1970-01-01
      • 2022-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多