可能重複:
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
可能重複:
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
在你.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()方法。
像這樣,您將覆蓋ECMA腳本5方法,也支持[支持它的瀏覽器](http://kangax.github.com/es5-compat-table/)。請添加一個條件。 – 2012-07-11 20:21:44
好,@BeatRichartz!我相應地更新了我的答案。 – 2012-07-12 06:44:37
通常沒有理由放棄時區信息。請參閱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';
};
}
您可以重新註冊該代碼嗎? – Bergi 2012-07-11 20:16:32
儘量不要丟失時區信息。請參閱http://stackoverflow.com/a/15302113/277267 – 2013-03-08 19:55:52