简体   繁体   English

时间解析行为

[英]time.Parse behaviour

In Go, while trying to convert string to time.Time , using time package's Parse method doesn't return expected result. 在Go中,尝试将字符串转换为time.Time ,使用时间包的Parse方法不会返回预期结果。 It seems problem is with the timezone. 似乎时区有问题。 I want to change to ISO 8601 combined with date and time in UTC. 我想将UTC中的日期和时间更改为ISO 8601。

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
}

thanks in advance! 提前致谢!

Your format string longForm is not correct. 您的格式字符串longForm不正确。 You would know that if you would have not been ignoring the returned error . 您将知道,如果您不忽略返回的错误 Quoting the docs : 引用文档

These are predefined layouts for use in Time.Format and Time.Parse. 这些是在Time.Format和Time.Parse中使用的预定义布局。 The reference time used in the layouts is: 布局中使用的参考时间为:

Mon Jan 2 15:04:05 MST 2006

which is Unix time 1136239445. Since MST is GMT-0700, the reference time can be thought of as 这是Unix时间1136239445。由于MST是GMT-0700,因此参考时间可以认为是

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

To define your own format, write down what the reference time would look like formatted your way; 要定义自己的格式,请写下参考时间,以哪种方式格式化; see the values of constants like ANSIC, StampMicro or Kitchen for examples. 有关示例,请参见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 操场


Output: 输出:

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

time.Parse uses special values for time formatting , and expecting the format to be passed with those values. time.Parse使用特殊值进行时间格式设置 ,并期望格式与这些值一起传递。

If you pass correct values, it will parse the time in the correct manner. 如果传递正确的值,它将以正确的方式解析时间。

So passing year as 2006, month as 01 and goes on like that... 因此,过去的年份为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>
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM