gpt4 book ai didi

parsing - time.Parse 行为

转载 作者:IT王子 更新时间:2023-10-29 02:25:40 30 4
gpt4 key购买 nike

在 Go 中,尝试将字符串转换为 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
}

提前致谢!

最佳答案

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

These are predefined layouts for use in Time.Format and 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

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.

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

关于parsing - time.Parse 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16536216/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com