dongzaizai2015 2018-09-04 14:42
浏览 29
已采纳

Golang中的编组/解组时间对象意外失败

Unmarshalling a marshalled time object is failing, because of a few characters

Test

declare the following:

// values
now := time.Now()
timeToJSON, _ := json.Marshal(now)
var obj time.Time
json.Unmarshal(timeToJSON, &obj)

then do the following test logic:

if !assert.Equal(t,
    now.String(),
    obj.String()) {
    t.FailNow()
}

Expected

the test to pass, and the two objects to be equal

Actual

It fails:

--- FAIL: TestFromJSON (0.00s)
    D:\dev2017\GO\src\ezsoft\apiserver_sdk\model\delete\deleteModel_test.go:94: 
            Error Trace:    deleteModel_test.go:94
            Error:          Not equal: 
                            expected: "2018-09-04 10:36:18.3627338 -0400 EDT m=+0.014000801"
                            actual  : "2018-09-04 10:36:18.3627338 -0400 EDT"

                            Diff:
                            --- Expected
                            +++ Actual
                            @@ -1 +1 @@
                            -2018-09-04 10:36:18.3627338 -0400 EDT m=+0.014000801
                            +2018-09-04 10:36:18.3627338 -0400 EDT
            Test:           TestFromJSON
FAIL
FAIL    ezsoft/apiserver_sdk/model/delete   1.336s
Error: Tests failed.

NOTE

I notice that, upon inspecting the output, that, somehow, some m=+[blah] is being appended to expected/actual.

I don't know why, however, and skimming RFC 3339 doesn't give me any hints why.

  • 写回答

2条回答 默认 最新

  • douchun1900 2018-09-04 14:47
    关注

    Per the documentation, the m value is the monotonic clock value, which can be removed using Truncate for comparisons not for the purpose of timing. The m field does not match because it is omitted from JSON, it is only generated by time.Now().

    Try like so:

    // values
    now := time.Now().Truncate(0)  // Truncate to remove monotonic clock portion
    timeToJSON, _ := json.Marshal(now)
    var obj time.Time
    json.Unmarshal(timeToJSON, &obj)
    

    The monotonic clock offset was added in order to allow for accurate timing of durations which span a wall clock change (e.g. NTP update, DST change, or leap second/smear).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 vb net 使用 sendMessage 如何输入鼠标坐标
  • ¥200 求能开发抖音自动回复卡片的软件
  • ¥15 关于freesurfer使用freeview可视化的问题
  • ¥100 谁能在荣耀自带系统MagicOS版本下,隐藏手机桌面图标?
  • ¥15 求SC-LIWC词典!
  • ¥20 有关esp8266连接阿里云
  • ¥15 C# 调用Bartender打印机打印
  • ¥15 我这个代码哪里有问题 acm 平台上显示错误 90%,我自己运行好像没什么问题
  • ¥50 C#编程中使用printDocument类实现文字排版打印问题
  • ¥15 找会编程的帅哥美女 可以用MATLAB里面的simulink编程,用Keil5编也可以。