【问题标题】:time.Parse behaviourtime.Parse 行为
【发布时间】:2013-05-08 07:45:09
【问题描述】:

在 Go 中,尝试将字符串转换为 time.Time 时,使用 time 包的 Parse 方法不会返回预期结果。似乎问题出在时区上。我想更改为 ISO 8601,并结合 UTC 日期和时间。

package main

import (
    "fmt"
    "time"
)

func main() {
    const longForm = "2013-05-13T18:41:34.848Z"
    //even this is not working
    //const longForm = "2013-05-13 18:41:34.848 -0700 PDT"
    t, _ := time.Parse(longForm, "2013-05-13 18:41:34.848 -0700 PDT")
    fmt.Println(t)
    //outputs 0001-01-01 00:00:00 +0000 UTC
}

提前致谢!

【问题讨论】:

    标签: parsing datetime time go timezone


    【解决方案1】:

    time.Parse 使用 special values for time formatting,并期望格式与这些值一起传递。

    如果您传递正确的值,它将以正确的方式解析时间。

    2006 年过去了,01 月份过去了,这样继续下去......

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
        const longForm = "2006-01-02 15:04:05.000 -0700 PDT"
        t, err := time.Parse(longForm, "2013-05-13 18:41:34.848 -0700 PDT")
        fmt.Println(t.UTC(), err)
        //outputs 2013-05-14 01:41:34.848 +0000 UTC <nil>
    }
    

    【讨论】:

    • 我也想知道如果我将值更改为2017-Oct-14,为什么它不起作用。谢谢你的解释。
    【解决方案2】:

    您的格式字符串longForm 不正确。 You would know that if you would have not been ignoring the returned error。引用docs

    这些是用于 Time.Format 和 Time.Parse 的预定义布局。布局中使用的参考时间是:

    Mon Jan 2 15:04:05 MST 2006
    

    这是 Unix 时间 1136239445。由于 MST 是 GMT-0700,所以参考时间可以认为是

    01/02 03:04:05PM '06 -0700
    

    要定义您自己的格式,请写下按照您的方式格式化的参考时间;例如,参见 ANSIC、StampMicro 或 Kitchen 等常量的值。

    package main
    
    import (
            "fmt"
            "log"
            "time"
    )
    
    func main() {
            const longForm = "2006-01-02 15:04:05 -0700"
            t, err := time.Parse(longForm, "2013-05-13 18:41:34.848 -0700")
            if err != nil {
                    log.Fatal(err)
            }
            fmt.Println(t)
    }
    

    Playground


    输出:

    2013-05-13 01:41:34.848 +0000 UTC
    

    【讨论】:

    • 感谢您的回答,但这不是我正在寻找的格式(2013-05-13 01:41:34.848 +0000 UTC),它不是提供的格式(“2006- 01-02 15:04:05 -0700") 并且什么都不会被忽略 :) 如果你更新你的答案,我会很高兴。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-21
    • 1970-01-01
    • 2011-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多