【问题标题】:Golang time.Parse() Behavior - Dropping Precision when 000Golang time.Parse() 行为 - 000 时降低精度
【发布时间】:2017-10-31 02:31:44
【问题描述】:

在 Go 中,我对在将日期字符串解析为 time.Time 时观察到的 time.Parse() 的行为感到困惑。

如果给定时间字符串的毫秒数正好等于“000”,例如"2017-01-02T01:02:03.000Z", time.Parse() 将截断 "000"。

为了日志记录和其他用例的一致性,最好包括而不是省略它。

这是预期的行为吗?如果有,为什么?

奖励:我们如何保留“000”?

Playground

package main

import (
    "log"
    "time"
)

func main() {

    const (
        ISO_8601 = "2006-01-02T15:04:05.999Z"
    )

    tMap := map[string]string{
        "t00": "2017-01-02T01:02:03.000Z",
        "t01": "2017-01-02T01:02:03.000Z",
        "t02": "2017-01-02T01:02:03.456Z",
        "t03": "2017-01-03T01:02:03.123Z",
        "t04": "2013-10-04T01:02:03.456Z",
        "t05": "2012-02-02T01:02:03.321Z",
        "t06": "2011-03-07T01:02:03.849Z",
    }

    for _, v := range tMap {
        t, err := time.Parse(ISO_8601, v)
        logFatal("0H N03Z!!1", err)

        // Dude where's my 000?
        log.Printf("Key: %s | lenTimeString: %d | Val: %s \n", t.String(), len(t.String()), t)
    }
}

func logFatal(hint string, e error) {
    if e != nil {
        log.Fatal(hint, e)
    }
}

输出:

2009/11/10 23:00:00 Key: t05 | lenTimeString: 33 | timeString: 2012-02-02 01:02:03.321 +0000 UTC 
2009/11/10 23:00:00 Key: t06 | lenTimeString: 33 | timeString: 2011-03-07 01:02:03.849 +0000 UTC 
2009/11/10 23:00:00 Key: t00 | lenTimeString: 29 | timeString: 2017-01-02 01:02:03 +0000 UTC 
2009/11/10 23:00:00 Key: t01 | lenTimeString: 29 | timeString: 2017-01-02 01:02:03 +0000 UTC 
2009/11/10 23:00:00 Key: t02 | lenTimeString: 33 | timeString: 2017-01-02 01:02:03.456 +0000 UTC 
2009/11/10 23:00:00 Key: t03 | lenTimeString: 33 | timeString: 2017-01-03 01:02:03.123 +0000 UTC 
2009/11/10 23:00:00 Key: t04 | lenTimeString: 33 | timeString: 2013-10-04 01:02:03.456 +0000 UTC 

编辑:在@zerkms 的帮助下,这是一个简化的解决方案

Play

package main

import (
    "fmt"
    "time"
)

func main() {

    p := fmt.Println

    const (
        ISO_8601           = "2006-01-02T15:04:05.000Z"
        ISO_8601_dropmilli = "2006-01-02T15:04:05.999Z"
    )

    t := time.Date(2017, time.October, 31, 15, 16, 17, 000000000, time.Local)

    p(t.Format(ISO_8601))
    p(t.Format(ISO_8601_dropmilli))
}

输出:

2017-10-31T15:16:17.000Z
2017-10-31T15:16:17Z

【问题讨论】:

    标签: parsing datetime go


    【解决方案1】:

    time.String 使用2006-01-02 15:04:05.999999999 -0700 MST 格式。

    要保持零使用0 而不是92006-01-02 15:04:05.000000000 -0700 MST

    t.Format("2006-01-02 15:04:05.000 -0700 MST")
    

    【讨论】:

    • 谢谢@zerkms。您能在我提供的游乐场链接的编辑中说明这一点吗?我想非常清楚如何应用您的建议。
    • “大声思考”,如果我们将 time.Time 转换为字符串,而不是将字符串转换为 time.Time,然后再转换回字符串,0 与 9 的相同用法会起作用吗? TODO:测试后在此处发布。
    • 我不确定我明白你的意思:-)
    • 我的意思是对任何对此行为感兴趣的人:play.golang.org/p/RgjVSRKdIr
    猜你喜欢
    • 1970-01-01
    • 2020-03-18
    • 1970-01-01
    • 2018-12-28
    • 2011-07-16
    • 2022-11-02
    • 2019-04-14
    • 2016-06-18
    • 2014-08-05
    相关资源
    最近更新 更多