转换一个正常的日期为ISO-8601格式

问题描述:

可能重复:
How do I output an ISO-8601 formatted string in Javascript?转换一个正常的日期为ISO-8601格式

我有一个像

Thu Jul 12 2012 01:20:46 GMT+0530 

日期我怎么能转换成ISO- 8601这样的格式

2012-07-12T01:20:46Z 
+0

尽量不要丢失时区信息。请参阅http://stackoverflow.com/a/15302113/277267 – 2013-03-08 19:55:52

在你.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

有日期的.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