使用 reviver 函数解析日期
- <!DOCTYPE html>
- <html>
- <body>
- <h1>把字符串转换为 date 对象</h1>
- <p id="demo"></p>
- <script>
- var text = '{"name":"Bill Gates", "birth":"1955-10-28", "city":"Seattle"}';
- var obj = JSON.parse(text, function (key, value) {
- if (key == "birth") {
- return new Date(value);
- } else {
- return value;
- }
- });
- document.getElementById("demo").innerHTML = obj.name + ", " + obj.birth;
- </script>
- </body>
- </html>