Question

I'm wondering what the best way is to perform the below functionality:

  1. Read an ISO 8601 timestamp, say from an attribute of a HTML element
  2. Check whether a certain amount of time has elapsed
  3. Do function() if this amount of time has elapsed

I could think of a few ways to attack this problem, but all of them seem a little clumsy and difficult to provide flexibility with. This doesn't have to update in real-time, but I am using jQuery and the TimeAgo plugin (https://github.com/rmm5t/jquery-timeago), so we may be able to do that.

I'm sure other people have done or attempted to do this, but have not seen any definitive answers.

For an example, I have the HTML:

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

and I want to insert a <span class="new">New!</span> element after this if the timestamp is less than, say, 10 minutes old.

We can do something like this to get us started:

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

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

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

What's the best way to compare the time?

Was it helpful?

Solution

Most modern browsers accept ISO 8601 within the date construtor. All you need to do is calculate the difference between now and then in minutes.

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

Explanation:

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

Usage:

$('abbr.timeago').each(function() {
  if ( isLessThan10MinAgo( $(this).attr('title') ) ) {
    $(this).after('<span class="new">New!</span>');
  }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top