PHP CodeBase: 将时间展示为“刚刚”“n分钟/小时前”等

WBOY
Release: 2016-06-13 13:01:57
Original
837 people have browsed it

PHP CodeBase: 将时间显示为“刚刚”“n分钟/小时前”等

在很多场合为了显示出信息的及时性,一般会将时间显示成“刚刚”,“5分钟前”,“3小时前”等,而不是直接将时间打印出来。比如微博,SNS类应用就最长用到这个功能。而一般存储在数据库中的时间格式为 Unix时间戳,所以这里记录一个将 Unix时间戳 转化为时间轴显示的PHP函数。

函数比较简单,直接看代码就很好懂了。


date_default_timezone_set('PRC');
$date = "1351836000";
echo tranTime($date);

function transfer_time($time)
{
    $rtime = date("m-d H:i",$time);
    $htime = date("H:i",$time);

    $time = time() - $time;

    if ($time     {
        $str = '刚刚';
    }
    elseif ($time     {
        $min = floor($time/60);
        $str = $min.'分钟前';
    }
    elseif ($time     {
        $h = floor($time/(60*60));
        $str = $h.'小时前 '.$htime;
    }
    elseif ($time     {
        $d = floor($time/(60*60*24));
        if($d==1)
            $str = '昨天 '.$rtime;
        else
            $str = '前天 '.$rtime;
    }
    else
    {
        $str = $rtime;
    }
    return $str;
}

?>

注意函数transfer_time()中的参数$time必须为Unix时间戳,如果不是请先用strtotime()将其转换成Unix时间戳

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!