1

我想知道执行以下功能的最佳方法是什么:

  1. 读取 ISO 8601 时间戳,例如从 HTML 元素的属性中读取
  2. 检查是否经过了一定的时间
  3. 如果这段时间已经过去,请执行 function()

我可以想出一些方法来解决这个问题,但是所有这些方法看起来都有些笨拙并且难以提供灵活性。这不必实时更新,但我使用的是 jQuery 和 TimeAgo 插件(https://github.com/rmm5t/jquery-timeago),所以我们可以做到这一点。

我敢肯定其他人已经这样做或试图这样做,但还没有看到任何明确的答案。

例如,我有 HTML:

<abbr class="timeago" title="2012-12-11T17:00:00">~6 hours ago</abbr>

<span class="new">New!</span>如果时间戳小于 10 分钟,我想在此之后插入一个元素。

我们可以做这样的事情来让我们开始:

$('abbr.timeago').each(function() {

    var timestamp = $(this).attr("title");

    if (function to compare time?) {
        $(this).insertAfter('<span class="new">New!</span>');
    }
});

比较时间的最佳方法是什么?

4

1 回答 1

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>');
  }
});
于 2012-12-12T03:58:37.387 回答