dssqq64884 2018-09-08 06:01
浏览 280
已采纳

为什么在bson.Marshal和bson.Unmarshal之后time.Time不相等?

Why does it output false? I was expecting true...

package main
import (
    "fmt"
    "time"
    "gopkg.in/mgo.v2/bson"
    )

type S struct {
    T time.Time
}
func main() {
    t := S{time.Now()}
    bytes, _ := bson.Marshal(t)
    var dt S
    bson.Unmarshal(bytes, &dt)
    fmt.Println(dt.T.Equal(t.T))
}

go run the above will output false, why Marshal/Unmarshal doesn't preserve the original value?

  • 写回答

1条回答 默认 最新

  • dongxieting9623 2018-09-08 07:11
    关注

    Bson stores time with lower precision than a time.Time, the value returned from Bson may not equal the value you stored. You need to use bson.Now():

    package main
    
    import (
        "fmt"
        "gopkg.in/mgo.v2/bson"
        "time"
    )
    
    type S struct {
        T time.Time
    }
    
    func main() {
        t := S{bson.Now()}
        bytes, _ := bson.Marshal(t)
        var dt S
        bson.Unmarshal(bytes, &dt)
        fmt.Println(dt.T)
        fmt.Println(t.T)
        fmt.Println(dt.T.Equal(t.T))
    }
    

    Output:

    $> go run main.go 
    2018-09-08 10:48:42.45 +0300 MSK
    2018-09-08 10:48:42.45 +0300 MSK
    true
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器