使用 reviver 函数解析日期

  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4.  
  5. <h1>把字符串转换为 date 对象</h1>
  6.  
  7. <p id="demo"></p>
  8.  
  9. <script>
  10. var text = '{"name":"Bill Gates", "birth":"1955-10-28", "city":"Seattle"}';
  11. var obj = JSON.parse(text, function (key, value) {
  12. if (key == "birth") {
  13. return new Date(value);
  14. } else {
  15. return value;
  16. }
  17. });
  18. document.getElementById("demo").innerHTML = obj.name + ", " + obj.birth;
  19. </script>
  20.  
  21. </body>
  22. </html>