javascript 将普通日期转换为 ISO-8601 格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11440569/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting a normal date to ISO-8601 format
提问by Bhoot
Possible Duplicate:
How do I output an ISO-8601 formatted string in Javascript?
I have a date like
我有一个像
Thu Jul 12 2012 01:20:46 GMT+0530
How can I convert it into ISO-8601 format like this
我怎样才能把它转换成这样的 ISO-8601 格式
2012-07-12T01:20:46Z
回答by Andrew Андрей Листочкин
In most newer browsers you have .toISOString()
method, but in IE8 or older you can use the following (taken from json2.jsby Douglas Crockford):
在大多数较新的浏览器中,您有.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;
}
Now you can safely call `.toISOString() method.
现在您可以安全地调用 `.toISOString() 方法。
回答by Beat Richartz
There's the .toISOString()
method on date. You can use that for Browsers with support for ECMA-Script 5. For those without, install the method like this:
有.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';
};
}