编组 time.Time 个对象时避免精度损失

Avoid precision loss when marshalling time.Time objects

我已经 go playground 重现了我的问题。我有一些失败的测试,因为 json Marshal 方法在 time.Time 对象的转换过程中似乎失去了精度。

运行 下面的代码:

package main

import (
    "fmt"
    "encoding/json"
    "time"
)

type myStruct struct{
    Now time.Time `json:"time"`
}

func main() {
    expect := &myStruct{Now: time.Now()}
    
    fmt.Println(expect.Now.String())
    
    byteData, err := json.Marshal(expect)
    if err != nil {
        panic(err.Error())
    }
    
    actual := &myStruct{}
    err = json.Unmarshal(byteData, &actual)
    if err != nil {
        panic(err.Error())
    }
    
    fmt.Println(actual.Now.String())
}

输出:

2009-11-10 23:00:00 +0000 UTC m=+0.000000001
2009-11-10 23:00:00 +0000 UTC

问题是,当我 运行 任何涉及转换 time.Time 对象的测试时,我无法使用任何标准方法来比较结果(证明、反映...)。

有没有办法在编组 time.Time 对象时保持精度,或者 'round' 将时间值设为较低的精度?

使用expect := &myStruct{Now: time.Now().Local()}expect := &myStruct{Now: time.Now().UTC()}。这将移除您的精密部件,您可以成功测试它。

也可以用Time.Round:

Round returns t stripped of any monotonic clock reading but otherwise unchanged.

所以:

time.Now().Round(0)

将去除单调偏移,使其余时间组件保持不变(时区等)