Below is a really nice time ago plugin for jQuery, very similar to what they use here on SO. The problem for me is that it uses this to convert time.
I had the same problem. I'm using Unix timestamps which are generated from PHP, so I decided to do a quick hack and extend the parsing function of jQuery timeago to handle timestamps additionally. Works like a charm. Simply look for the Parse function at around line 79 in the jquery.timeago.js file, and replace with the following:
parse: function(iso8601) {
if ((iso8601 - 0) == iso8601 && iso8601.length > 0) { // Checks if iso8601 is a unix timestamp
var s = new Date(iso8601);
if (isNaN(s.getTime())) { // Checks if iso8601 is formatted in milliseconds
var s = new Date(iso8601 * 1000); //if not, add milliseconds
}
return s;
}
var s = $.trim(iso8601);
s = s.replace(/-/,"/").replace(/-/,"/");
s = s.replace(/T/," ").replace(/Z/," UTC");
s = s.replace(/([\+-]\d\d)\:?(\d\d)/," $1$2"); // -04:00 -> -0400
return new Date(s);
},
It would be better using both, but it is not necessary to make it dynamic with JS.
In fact, I've only seen this behaviour in Facebook.
Also, are you well aware that the <time>
tag is HTML5? It may create a few uncompatibilities.
I like to use DateJS.com which is a date / time javascript library. You can do cool stuff like this (display 2 hours ago in a <span id='myfield'></span>
):
$('#myfield').text( (2).hours().ago().toString("HH:mm") );
Here is something in JavaScript using nothing but Unix timestamps.
var d1;
var d2;
d1 = (new Date()).getTime(); setTimeout( function() { d2 = (new Date()).getTime(); }, 5000 );
var secondsElapsed = (d2 - d1) / 1000;
secondsElapsed; // 5 seconds
Now, you can either store a timestamp in a JavaScript variable in the same scope as your "timeago" function, or your can store it in an HTML element. As mentioned, the time
element is an HTML 5 element. You could do something like:
<p class="timestamp" style="display: none;">123456</p>
Then maybe you have a comment item like:
<div class="comment">
<p>Lorem ipsum et dolor...</p>
<p class="timestamp" style="display: none;">123456</p>
</div>
You could then get the timestamp for a comment by (assuming jQuery since you mentioned it):
var tstamps = $('.comment .timestamp'); // array of comment timestamps
var timeago = ( (new Date()).getTime() - tstamps[0].html() ) / 1000;
It's a bit hackish, but it would work (if I did it right).