如何在JavaScript中输出ISO 8601格式的字符串? [英] How do I output an ISO 8601 formatted string in JavaScript?
本文介绍了如何在JavaScript中输出ISO 8601格式的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个日期
对象。 如何呈现以下代码段的标题
部分?
I have a Date
object. How do I render the title
portion of the following snippet?
<abbr title="2010-04-02T14:12:07">A couple days ago</abbr>
我有另一个图书馆的相对时间部分。
I have the "relative time in words" portion from another library.
我尝试过以下操作:
function isoDate(msSinceEpoch) {
var d = new Date(msSinceEpoch);
return d.getUTCFullYear() + '-' + (d.getUTCMonth() + 1) + '-' + d.getUTCDate() + 'T' +
d.getUTCHours() + ':' + d.getUTCMinutes() + ':' + d.getUTCSeconds();
}
但这给了我:
"2010-4-2T3:19"
推荐答案
已经有一个名为 toISOString()
:
There is already a function called toISOString()
:
var date = new Date();
date.toISOString(); //"2011-12-19T15:28:46.493Z"
如果,不知何故,你是关于浏览器不支持,我已经覆盖了:
If, somehow, you're on a browser that doesn't support it, I've got you covered:
if ( !Date.prototype.toISOString ) {
( function() {
function pad(number) {
var r = String(number);
if ( r.length === 1 ) {
r = '0' + r;
}
return r;
}
Date.prototype.toISOString = function() {
return this.getUTCFullYear()
+ '-' + pad( this.getUTCMonth() + 1 )
+ '-' + pad( this.getUTCDate() )
+ 'T' + pad( this.getUTCHours() )
+ ':' + pad( this.getUTCMinutes() )
+ ':' + pad( this.getUTCSeconds() )
+ '.' + String( (this.getUTCMilliseconds()/1000).toFixed(3) ).slice( 2, 5 )
+ 'Z';
};
}() );
}
这篇关于如何在JavaScript中输出ISO 8601格式的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文