I’m wondering what the best way is to perform the below functionality:
- Read an ISO 8601 timestamp, say from an attribute of a HTML element
- Check whether a certain amount of time has elapsed
- 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?
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.
Explanation:
Usage: