这是一件真正简洁的事情(至少我相信是这样:)),不需要克隆任何日期就可以操作或重载toJSON等浏览器的任何本机功能(参考:如何对JSON日期进行JSON字符串化并保留时区,Coursy Shawson)
将替换器函数传递给JSON.stringify,以将内容字符串化为您内心的所有内容!!!这样,您就不必进行小时和分钟的差异或其他任何操作。
我已经输入console.logs来查看中间结果,因此很清楚正在发生什么以及递归如何工作。这揭示了一些值得注意的东西:替换者的值参数已转换为ISO日期格式:)。使用此[键]处理原始数据。
var replacer = function(key, value)
{
var returnVal = value;
if(this[key] instanceof Date)
{
console.log("replacer called with key - ", key, " value - ", value, this[key]);
returnVal = this[key].toString();
/* Above line does not strictly speaking clone the date as in the cloned object
* it is a string in same format as the original but not a Date object. I tried
* multiple things but was unable to cause a Date object being created in the
* clone.
* Please Heeeeelp someone here!
returnVal = new Date(JSON.parse(JSON.stringify(this[key]))); //OR
returnVal = new Date(this[key]); //OR
returnVal = this[key]; //careful, returning original obj so may have potential side effect
*/
}
console.log("returning value: ", returnVal);
/* if undefined is returned, the key is not at all added to the new object(i.e. clone),
* so return null. null !== undefined but both are falsy and can be used as such*/
return this[key] === undefined ? null : returnVal;
};
ab = {prop1: "p1", prop2: [1, "str2", {p1: "p1inner", p2: undefined, p3: null, p4date: new Date()}]};
var abstr = JSON.stringify(ab, replacer);
var abcloned = JSON.parse(abstr);
console.log("ab is: ", ab);
console.log("abcloned is: ", abcloned);
/* abcloned is:
* {
"prop1": "p1",
"prop2": [
1,
"str2",
{
"p1": "p1inner",
"p2": null,
"p3": null,
"p4date": "Tue Jun 11 2019 18:47:50 GMT+0530 (India Standard Time)"
}
]
}
Note p4date is string not Date object but format and timezone are completely preserved.
*/
2009-09-28T10:00:00Z
在时间不表示同一时刻的Mon Sep 28 10:00:00 UTC+0200 2009
。将Z
在ISO 8601日期指UTC和UTC在10点是不同的时间一瞬间到+0200 10点。希望将日期与正确的时区序列化是一回事,但是您要我们帮助您将日期序列化为明确,客观上是错误的表示形式。