Home  >  Article  >  Web Front-end  >  Solution to the inaccurate date and time when JSON.stringify converts JSON_javascript skills

Solution to the inaccurate date and time when JSON.stringify converts JSON_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:40:091827browse

When calling JSON.stringify to convert the object into the corresponding string, if it contains a time object, the time object will be converted to national standard time (ISO) instead of the time of the current country and region. The test code is as follows:

Copy code The code is as follows:

<script><br> //var o = new Date();<br> //console.log(o.toString())//China time zone time, format such as "Wed Jun 11 2014 10:51:42 GMT 0800"<br> //console.log(JSON.stringify(o)); //Output International Standard Time (ISO), reduced by 8 hours. The format is such as "2014-06-11T02:51:42.624Z"<br> </script>

If you want JSON.stringify to convert the date object Date and return the time zone of the current country instead of the international standard time, you can override the toJSON method of the prototype of the Date object to return a custom time format, because JSON.stringify calls Date The toJSON method of the object, the example is as follows:

Copy code The code is as follows:

<script><br> Date.prototype.toJSON = function () { return this.toLocaleString(); }<br> var o = new Date();<br> console.log(o.toString())//Default format: "Wed Jun 11 2014 10:51:42 GMT 0800"<br> console.log(JSON.stringify(o)); //Output the customized local time: "June 11, 2014 10:57:27"<br> </script>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn