使用JSON.stringify()和JSON.parse()时Date()的问题

时间:2012-07-15 12:34:47

标签: 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));

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

那么在这种情况下我该怎么办?有没有解决这个问题?

3 个答案:

答案 0 :(得分:49)

如果您查看日期的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

答案 1 :(得分:23)

JSON.stringify(new Date())

返回

  

“2013-10-06T15:32:18.605Z”

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

答案 2 :(得分:0)

正如推荐的答案所暗示的那样,在使用 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.stringify 时进入 JSON.parse 的内容是相同的。

如果您有两个毫秒值,使用 <> 也可以轻松比较日期。

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

const millis = Date.now();

console.log(millis);

console.log(new Date(millis));

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