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 w开发者_如何学Goould 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 http://img528.imageshack.us/img528/5442/35118769.png
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.
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.
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.
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.
精彩评论