可能是重复问题:
如何在JavaScript中输出ISO-8601格式的字符串?
我有一个日期,例如
Thu Jul 12 2012 01:20:46 GMT+0530
我该如何将它转换为 ISO-8601 格式,就像这样
2012-07-12T01:20:46Z
可能是重复问题:
如何在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-Script 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';
};
}