DIV CSS 佈局教程網

JSON.stringify 轉換日期時間不準確的解決方法
編輯:關於JavaScript     

呼叫 JSON.stringify 將物件轉為字串時,如果物件中包含時間物件,時間會被轉換為國際標準時間(ISO),而非當前國家區域的時間。測試程式碼如下:

<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 方法。示例如下:

<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>

透過覆寫 toJSON,就能讓序列化後的日期以本地時區格式呈現,避免少了八小時的困擾。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved