开发者

Display date and time something like blog

I have a blog. Regularly I post some fun thing. I maintain the timestamps for response times. How do I display the time like the following?

  • 2010-02-09 1 hour before, if the reply is just 1 hour old

  • 2010-02-09 20 hour before, if the reply is just 20 hour old

  • 2010-02-08 yesterday, if the reply is just 1 day old

  • 2010-02-04 17:20, if the reply is a couple of days before

I am maintaining the timestamp in a database as a Unix time. For example my timestamp is开发者_如何转开发 1265709142.

How can this be implemented with PHP?


$d = time() - $timestamp;
if ($d < 60)
    return $d." second".(($d==1)?'':'s')." ago";
else
{
    $d = floor($d / 60);
    if($d < 60)
        return $d." minute".(($d==1)?'':'s')." ago";
    else
    {
        $d = floor($d / 60);
        if($d < 24)
            return $d." hour".(($d==1)?'':'s')." ago";
        else
        {
            $d = floor($d / 24);
            if($d < 7)
                return $d." day".(($d==1)?'':'s')." ago";
            else
            {
                $d = floor($d / 7);
                if($d < 4)
                    return $d." week".(($d==1)?'':'s')." ago";
            }//Week
        }//Day
    }//Hour
}//Minute


I'm sure there are PHP based approaches for this and I'm interested to see some, but there is also a jQuery based plugin named Pretty Date. I think Stack Overflow uses that.

It depends of course on JavaScript being activated in the user's browser, but degrades gracefully when JavaScript is off. Also, in search engines, the real date is indexed and not the formatted date - a small but nice plus.


There is a JavaScript library for that: http://tpgblog.com/cutetime/. Just print your dates in a certain format and add the JavaScript library to your page. Done.


The best thing is to format the time according to ISO, e.g. 2008-07-17T09:24:17Z

<?php 
  $DateOfRequest = date("Y-m-dTH:i:s", $timestamp); 
?> 

Then, use http://timeago.yarp.com/ to inject format strings like "2 hours ago" or so.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜