我想知道执行以下功能的最佳方法是什么:
我可以想出几种方法来解决这个问题,但是所有这些方法看起来都有些笨拙且很难提供灵活性。这不需要实时更新,但我使用的是jQuery和TimeAgo插件(https://github.com/rmm5t/jquery-timeago),所以我们可以做到这一点。
我确信其他人已经或试图这样做,但没有看到任何确定的答案。
举个例子,我有HTML:
<abbr class="timeago" title="2012-12-11T17:00:00">~6 hours ago</abbr>
如果时间戳小于10分钟,我想在此之后插入一个<span class="new">New!</span>
元素。
我们可以做这样的事情让我们开始:
$('abbr.timeago').each(function() {
var timestamp = $(this).attr("title");
if (function to compare time?) {
$(this).insertAfter('<span class="new">New!</span>');
}
});
比较时间的最佳方式是什么?
答案 0 :(得分:1)
大多数现代浏览器都接受日期构造中的ISO 8601。您需要做的就是计算现在和之间的差异,以分钟为单位。
function isLessThan10MinAgo( date ) {
return 0|(new Date() - new Date( date )) * 1.67e-5 <= 10;
}
// Current time: 22:52
console.log( isLessThan10MinAgo('2012-12-11T22:48:00-05:00')); //=> true
console.log( isLessThan10MinAgo('2012-12-11T22:12:00-05:00')); //=> false
说明:
0| // floor the result
(new Date() - new Date( date ) // obtain difference between now and then in ms.
* 1.67e-5 // convert to aprox. minutes
<= 10 // return whether is less than 10 min
用法:
$('abbr.timeago').each(function() {
if ( isLessThan10MinAgo( $(this).attr('title') ) ) {
$(this).after('<span class="new">New!</span>');
}
});