Issues with Date() when using JSON.stringify() and JSON.parse()

后端 未结 2 820
攒了一身酷
攒了一身酷 2020-12-01 10:33

I am trying to calculate the difference between two times using JavaScript. It\'s just basic math but I seem to have some issues with that while using JSON.stringify()

相关标签:
2条回答
  • 2020-12-01 10:46

    If you look at the output of JSON.stringify for a Date, you'll see that:

    JSON.stringify(new Date())
    

    Results in a string. JSON does not have a primitive representation of Date objects that JSON.parse will turn back into a Date object automatically.

    The Date object's constructor can take a date string, so you can turn those string values back into dates by doing:

    var x = new Date(JSON.parse(JSON.stringify(new Date())));
    

    Then the arithmetic will work.

    x = new Date(JSON.parse(JSON.stringify(new Date())))
    y = new Date(JSON.parse(JSON.stringify(new Date())))
    y - x
    => 982
    
    0 讨论(0)
  • 2020-12-01 11:00
    JSON.stringify(new Date())
    

    returns

    "2013-10-06T15:32:18.605Z"

    Thank God is: Date.prototype.toISOString()

    0 讨论(0)
提交回复
热议问题