源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

JSON.stringify转换JSON时日期时间不准确的解决方法

  • 时间:2022-06-01 20:59 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:JSON.stringify转换JSON时日期时间不准确的解决方法
调用JSON.stringify将对象转为对应的字符串时,如果包含时间对象,时间对象会被转换为国家标准时间(ISO),而不是当前国家区域的时间,测试代码如下: [img]http://files.jb51.net/file_images/article/201408/201488110041640.jpg?20147811130[/img]
[u]复制代码[/u] 代码如下:
<script>     //var o = new Date();     //console.log(o.toString())//中国时区时间,格式如“Wed Jun 11 2014 10:51:42 GMT+0800”     //console.log(JSON.stringify(o)); //输出国际标准时间(ISO),减少了8个小时 格式如“2014-06-11T02:51:42.624Z” </script>
要想JSON.stringify转换日期对象Date返回当前所在国家的时区,而不是国际标准时间,可以重写Date对象的prototype的toJSON方法,返回自定义时间格式,因为JSON.stringify调用的就是Date对象的toJSON方法,示例如下: [img]http://files.jb51.net/file_images/article/201408/201488110144422.jpg?20147811211[/img]
[u]复制代码[/u] 代码如下:
<script>     Date.prototype.toJSON = function () { return this.toLocaleString(); }     var o = new Date();     console.log(o.toString())//默认格式:“Wed Jun 11 2014 10:51:42 GMT+0800”     console.log(JSON.stringify(o)); //输出自定义的本地时间:“2014年6月11日 10:57:27” </script>
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部