使用JSON.stringify()和JSON.parse()时,Date()出现问题

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

本文关键字:JSON Date 问题 parse stringify 使用      更新时间:2023-09-26

我正在尝试使用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));

以上将返回null。此外,当我想查看Math.floor(x)结果时,它会再次返回null

那么在这种情况下我该怎么办呢?有解决办法吗?

如果您查看日期的JSON.stringify的输出,您会看到:

JSON.stringify(new Date())

结果为字符串。JSON没有Date对象的基元表示,JSON.parse将自动将其转换回Date对象。

Date对象的构造函数可以采用日期字符串,因此您可以通过执行以下操作将这些字符串值转换回日期:

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

然后算术就行了。

x = new Date(JSON.parse(JSON.stringify(new Date())))
y = new Date(JSON.parse(JSON.stringify(new Date())))
y - x
=> 982
JSON.stringify(new Date())

返回

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

感谢上帝是:Date.prototype.toISOString()

正如建议的答案所示,使用JSON.stringify时,只需将日期转换为字符串即可。

另一种可能适合此用例的方法是使用Date.now():以毫秒为单位存储时间

// Date.now() instead of new Date()
const millis = Date.now();
console.log(millis);
// same output as input
console.log(JSON.parse(JSON.stringify(millis)));

这样,当使用JSON.parse时,您可以确保进入JSON.stringify的内容是相同的。

如果您有两个毫秒值,使用<>也可以很容易地比较日期。

此外,您可以随时将毫秒转换为日期(通常在您将其呈现给用户之前):

const millis = Date.now();
console.log(millis);
console.log(new Date(millis));

注意:通常不建议使用毫秒作为日期表示,至少在数据库中不建议使用:https://stackoverflow.com/a/48974248/10551293.