【问题标题】:Issues with Date() when using JSON.stringify() and JSON.parse()使用 JSON.stringify() 和 JSON.parse() 时的 Date() 问题
【发布时间】:2012-07-14 13:41:32
【问题描述】:

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

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

【问题讨论】:

  • 你可以通过使用像 rhaboo 这样的 localStorage 包装器而不是 stringify/parse 来避免这样的仇恨,除了这个之外还有许多其他的不准确之处。

标签: javascript json date


【解决方案1】:

如果你查看 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 规范没有定义如何处理日期,但从 ECMAScript 2016 开始,ECMA-262 定义了。实现应该使用Date.prototype.toJSON,它为toISOString 创建一个ISO 8601 字符串(它使用相同的方法)。但你可能在 2012 年还没有做到这一点…… ;-)
  • 人们会期望 JSON.parse(JSON.stringify(new Date())) 返回一个 Date 对象(例如数字)。我看不到当前行为在哪里有用。任何想法为什么不是这样的默认值:_jsonUTCDateFormat = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/; fromJson(jsonString: string) { return JSON.parse(jsonString, (key, value) => { if (typeof value === "string" && this._jsonUTCDateFormat.test(value)) { return this.parseUTCDate(value); } return value; }); }
【解决方案2】:
JSON.stringify(new Date())

返回

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

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

【讨论】:

  • 很高兴知道JSON.stringify() 在幕后使用Date.toISOString()。这使我的代码更加清晰。
【解决方案3】:

正如推荐的答案所示,使用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。

【讨论】:

    猜你喜欢
    • 2014-07-06
    • 2015-01-25
    • 2018-03-10
    • 2021-04-16
    • 2022-01-25
    • 1970-01-01
    • 2015-06-29
    • 2011-11-01
    相关资源
    最近更新 更多