views:

105

answers:

3

Hello,

I have page where where I list all comments for a post. Next to each comment I have a time value in full format including the date/time (2010-01-02 11:11:20).

I know that I can format it in PHP before displaying it, so it shows;

posted 40 secs ago 
posted 5 days ago

but that would not be efficient as I am going to cache the page once it is generated.

On SO I see that they have some kind of java script for showing it, so it is run on the browser of the client:

alt text

So basically I need a java script that runs on the browser that would instead of showing my date/time show "posted 4 hours ago". All help is welcome.

A: 

Output your date in a format accepted by the parseDate method or as a constructor parameter for date. Place them in some nodes which can later on easily be grabbed by a javascript framework (or your own methods) and then perform some time/datediff methods on these grabbed values and replace the node's content.

tDo
+8  A: 

Sounds you want this: timeago: a jQuery plugin.

Timeago is a jQuery plugin that makes it easy to support automatically updating fuzzy timestamps (e.g. "4 minutes ago" or "about 1 day ago").

I quote further:

  • Avoid timestamps dated "1 minute ago" even though the page was opened 10 minutes ago; timeago refreshes automatically.

  • You can take full advantage of page caching in your web applications, because the timestamps aren't calculated on the server.

So it should fit your needs.

Felix Kling
+1 - Nice find on this plug-in. Seems to perfectly solve the OP's problem.
sberry2A
+1 I saw this plugin a few days ago and have been looking forward to using it in an upcoming project. Excellent solution.
Jonathan Sampson
Thx, the funny point: I saw it on SO as advertisement in the right column (some weeks ago) ;)
Felix Kling
Thank you all. I tend to ignore ads, well guess I am wrong :)
Adnan
+2  A: 

You can put the "timestamp" of the page into the page when you render it. This is the fixed time that doesn't change. Look at PHP's time function for this (http://www.php.net/manual/en/function.time.php). It gives you seconds since the UNIX epoch started.

Then, when the page is running, use Javascript's Date object. It encapsulates something similar. Do a getTime() on a new Javascript Date object, which will get you also seconds since the UNIX epoch.

Subtract one from the other to get the elapsed time between then and now, and do whatever pretty formatting you need to make it display right in your page.

Edit: See also Felix's answer about timeago, which is a nifty tool to do the second half of this process for you automatically.

quixoto
+1 - This is how you do it without that "nifty tool".
sberry2A