Rol*_*and 33 javascript json date
我试图用JavaScript计算两次之间的差异.这只是基本的数学,但在使用JSON.stringify()和时,我似乎遇到了一些问题JSON.parse().
如果您想知道为什么我将该JSON.stringify()功能应用于日期,那是因为我使用本地存储在客户端存储一些数据并在客户端再次登陆我的网站时使用它(它更快,而不是提出更多请求到服务器).这些数据通常会偶尔更新(我通过其他网站的API抓取数据),所以我设置了一个data_update变量,我将它与其他数据一起存储.
这样我就可以从本地存储中获取存储的数据并检查它们之间的差异data_update(这是一个日期/时间)和检查它之间的时间/日期,看它是否大于一周/天/等.
这就是我使用JSON函数的原因.我的问题是,当我从本地存储解析数据时,日期似乎与Date()对象不同.
我试图按照说法进行下一步操作:
var x = JSON.parse(JSON.stringify(new Date()));
var y = JSON.parse(this.get_local_storage_data(this.data_cache_key)); // the data object stored on local storage
var q = y.data_update; // this is the variable where the Date() was stored
console.log(Math.floor((x-q)/1000));
Run Code Online (Sandbox Code Playgroud)
以上将返回null.此外,当我想看到Math.floor(x)结果时,它会null再次返回.
那么在这种情况下我该怎么办?有没有解决这个问题?
Kyl*_*ton 54
如果你看一下Date的JSON.stringify输出,你会看到:
JSON.stringify(new Date())
Run Code Online (Sandbox Code Playgroud)
结果是一个字符串.JSON没有Date对象的原始表示,JSON.parse将自动转回Date对象.
Date对象的构造函数可以使用日期字符串,因此您可以通过执行以下操作将这些字符串值转换回日期:
var x = new Date(JSON.parse(JSON.stringify(new Date())));
Run Code Online (Sandbox Code Playgroud)
然后算术将起作用.
x = new Date(JSON.parse(JSON.stringify(new Date())))
y = new Date(JSON.parse(JSON.stringify(new Date())))
y - x
=> 982
Run Code Online (Sandbox Code Playgroud)
Luc*_*ato 23
JSON.stringify(new Date())
Run Code Online (Sandbox Code Playgroud)
回报
"2013-10-06T15:32:18.605Z"
感谢上帝是: Date.prototype.toISOString()
| 归档时间: |
|
| 查看次数: |
47182 次 |
| 最近记录: |