2012-07-11 72 views

回答

26

在你.toISOString()方法大多數較新的瀏覽器,但在IE8或以上,你可以使用下面的(由Douglas Crockford的從json2.js拍攝):

// Override only if native toISOString is not defined 
if (!Date.prototype.toISOString) { 
    // Here we rely on JSON serialization for dates because it matches 
    // the ISO standard. However, we check if JSON serializer is present 
    // on a page and define our own .toJSON method only if necessary 
    if (!Date.prototype.toJSON) { 
     Date.prototype.toJSON = function (key) { 
      function f(n) { 
       // Format integers to have at least two digits. 
       return n < 10 ? '0' + n : n; 
      } 

      return this.getUTCFullYear() + '-' + 
       f(this.getUTCMonth() + 1) + '-' + 
       f(this.getUTCDate())  + 'T' + 
       f(this.getUTCHours())  + ':' + 
       f(this.getUTCMinutes()) + ':' + 
       f(this.getUTCSeconds()) + 'Z'; 
     }; 
    } 

    Date.prototype.toISOString = Date.prototype.toJSON; 
} 

現在你可以安全地調用`.toISOString()方法。

+2

像這樣,您將覆蓋ECMA腳本5方法,也支持[支持它的瀏覽器](http://kangax.github.com/es5-compat-table/)。請添加一個條件。 – 2012-07-11 20:21:44

+0

好,@BeatRichartz!我相應地更新了我的答案。 – 2012-07-12 06:44:37

+1

通常沒有理由放棄時區信息。請參閱http://stackoverflow.com/a/15302113/277267 – 2013-03-08 19:56:44

6

有日期的.toISOString()方法。您可以使用 - 瀏覽器與ECMA腳本5.對於那些不支持,安裝這樣的方法:

if (!Date.prototype.toISOString) { 
    Date.prototype.toISOString = function() { 
     function pad(n) { return n < 10 ? '0' + n : n }; 
     return this.getUTCFullYear() + '-' 
      + pad(this.getUTCMonth() + 1) + '-' 
      + pad(this.getUTCDate()) + 'T' 
      + pad(this.getUTCHours()) + ':' 
      + pad(this.getUTCMinutes()) + ':' 
      + pad(this.getUTCSeconds()) + 'Z'; 
    }; 
} 
+0

您可以重新註冊該代碼嗎? – Bergi 2012-07-11 20:16:32

相關問題