问题描述
{ id: 1533,
story_type_id: 1,
content_id: 470,
created_at: Sun, 05 Feb 2012 07:02:43 GMT,
updated_at: Sun, 05 Feb 2012 07:02:43 GMT,
type_name: 'post' }
我有一个带有datetime字段的JSON对象,如上所示。这是完美的。但是当我将其字符串化时(我想将其存储在缓存中),我得到以下格式:
I have a JSON object with the "datetime" field like above. It's perfect. But when I stringify it (I want to store it in cache), I get this format:
"created_at":"2012-02-05T07:02:43.000Z"
这会导致问题,因为当我想要JSON时。解析这个,突然它不再是日期时间格式,它与我的其他格式不兼容。
This causes problems, because when I want to JSON.parse this, suddenly it's no longer datetime format and it's incompatible with my other format.
我该怎么做才能解决这个问题?在我的应用程序中,我的'created_at'遍布各处。我不想手动更改每一个。
What can I do to solve this problem? I have 'created_at' littered everywhere throughout my application. I don't want to manually change each one.
推荐答案
没有特殊的方法来序列化日期
JSON中的对象。这就是你获得标准化字符串表示的原因。您需要将它们转换回 Date
对象,方法是将它们传递给 Date
构造函数。
There is not special way to serialize Date
objects in JSON. That's why you get the standardized string representation. You need to convert them back to Date
objects by passing them to the Date
constructor.
item['created_at'] = new Date(item['created_at']);
更新:使用 reviver
函数(请参阅注释),您可以返回日期
对象。
Update: With the reviver
function (see comments), you can get the Date
objects back.
var item = JSON.parse(row, function (key, value) {
if (key === 'created_at') {
return new Date(value);
} else {
return value;
}
});
这篇关于为什么JSON.stringify搞砸了我的日期时间对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!