Golang time.Parse()行为 - 当000时降低精度

时间:2017-10-31 02:31:45

标签: parsing datetime go

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

如果给定的时间字符串的毫秒数恰好等于" 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

1 个答案:

答案 0 :(得分: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")