当调用JSON.stringify将一个对象转换为对应的字符串时,如果包含时间对象,则时间对象将被转换为国家标准时间(ISO),而不是当前国家和地区的时间。测试代码如下:
复制代码如下: script//var o=new Date();//console.log(o.toString())//中文时区,如“wed jun 11 2014 10336051336042 GM 0800”//console . log(JSON . stringfy(o));//输出国际标准时间(ISO),格式缩减8小时,如“2014-06-11t 02:51336042.624 z”/脚本。
如果希望JSON.stringify转换Date对象以返回当前国家的时区,而不是国际标准时间,可以重写Date对象原型的toJSON方法并返回自定义时间格式,因为JSON.stringify调用Date对象的toJSON方法。示例如下:
复制代码如下: script date . prototype . to JSON=function(){ return this . tolocalstring();} var o=新日期();Console.log(o.toString())//默认格式:“wedjon 11 2014 10:51336042 GMT 0800”console . log(JSON . stringfy(o));//输出用户自定义当地时间:“2014年6月11日,10:57:27”/脚本。