【问题标题】:If certain time elapsed from ISO 8601 timestamp, perform specified function如果从 ISO 8601 时间戳经过一定时间,则执行指定的功能
【发布时间】:2012-11-29 17:18:15
【问题描述】:

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

  1. 从 HTML 元素的属性中读取 ISO 8601 时间戳
  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>

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

我们可以这样做让我们开始:

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

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

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

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

【问题讨论】:

    标签: jquery time iso timeago elapsed


    【解决方案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>');
      }
    });
    

    【讨论】:

    • 对您的答案的评论,该函数返回 1(将被视为真)或 0(假)实际上不是真或假。所以我想我们必须添加if ( isLessThan10MinAgo( $(this).attr('title') ) == 1 ) { $(this).after('&lt;span class="new"&gt;New!&lt;/span&gt;'); } 我正在努力实现它。感谢您的回答,这似乎是一个不错的方法!
    • 0 是假的,1 是真的你不需要比较,但你总是可以像这样用!! 转换布尔值:return !!(0|(new Date() - new Date( date )) * 1.67e-5 &lt;= 10)
    • 代码对我来说似乎是正确的,但我无法让它真正工作。其余代码一定有问题(插入新&lt;span&gt;&lt;/span&gt;的部分?这是一个带有简化示例的jsfiddle。我以将来设置日期方式为例,因此函数的结果将始终是 1.jsfiddle.net/7cHZa/9 有什么想法吗?
    • 嗯...你的小提琴中没有包含 jQuery 库。
    • 但是,现在我正在尝试在实时站点上使用它,当我将代码粘贴到 Chrome 控制台时,我收到 SyntaxError: Unexpected token ILLEGAL 哦,不……有什么想法吗?
    猜你喜欢
    • 2013-03-11
    • 2023-04-11
    • 2013-12-06
    • 1970-01-01
    • 2019-02-02
    • 1970-01-01
    • 1970-01-01
    • 2012-02-13
    • 2021-10-24
    相关资源
    最近更新 更多