在golang中,Time.Format()会从小数部分删除尾随的零。

8
我该如何防止Go的Time.Format()函数去掉时间戳中小数部分末尾的零?以下是我编写的单元测试失败的代码。
package main

import (
    "testing"
    "time"
)

func TestTimeFormatting(t *testing.T) {
    timestamp := time.Date(2017, 1,2, 3, 4, 5, 600000*1000, time.UTC)
    timestamp_string := timestamp.Format("2006-01-02T15:04:05.999-07:00")
    expected := "2017-01-02T03:04:05.600+00:00"

    if expected != timestamp_string {
        t.Errorf("Invalid timestamp formating, expected %v, got %v", expected, timestamp_string)
    }
}

输出:

$ go test
--- FAIL: TestTimeFormatting (0.00s)
    main_test.go:14: Invalid timestamp formating, expected 2017-01-02T03:04:05.600+00:00, got 2017-01-02T03:04:05.6+00:00
FAIL
exit status 1
FAIL    _/home/sasa/Bugs/go-formatter   0.001s

有什么办法可以解决这个问题吗?
1个回答

13
啊,文档中已经有了。如果想要保留零,则应使用000而不是999。
package main

import (
    "testing"
    "time"
)

func TestTimeFormatting(t *testing.T) {
    timestamp := time.Date(2017, 1,2, 3, 4, 5, 600000*1000, time.UTC)
    timestamp_string := timestamp.Format("2006-01-02T15:04:05.000-07:00")
    expected := "2017-01-02T03:04:05.600+00:00"

    if expected != timestamp_string {
        t.Errorf("Invalid timestamp formating, expected %v, got %v", expected, timestamp_string)
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接