日期比较是程序开发经常遇到的问题,可以返回给定的两个时间之间的距离,并显示成易于读取的格式。
代码如下:
Example Source Code
<?php
// 说明:比较两个时间的差别并且显示为易于读取的格式
// 整理:will2011 http://www.51itrencai.com
function human_time_diff($from,$to='')
{
if(empty($to)) $to = time();
$diff = (int)abs($to - $from);
if($diff <= 3600)
{
$mins = round($diff / 60);
if($mins <= 1) $since = '1 min';
else $since = sprintf( '%s mins', $mins);
}
else if(($diff <= 86400) && ($diff > 3600))
{
$hours = round($diff / 3600);
if ($hours <= 1) $since = '1 hour';
else $since = sprintf( '%s hours', $hours );
}
elseif ($diff >= 86400)
{
$days = round($diff / 86400);
if ($days <= 1) $since = '1 day';
else $since = sprintf( '%s days', $days );
}
return $since;
}
echo human_time_diff( '1166454231', '2166592806' );
?>
// 说明:比较两个时间的差别并且显示为易于读取的格式
// 整理:will2011 http://www.51itrencai.com
function human_time_diff($from,$to='')
{
if(empty($to)) $to = time();
$diff = (int)abs($to - $from);
if($diff <= 3600)
{
$mins = round($diff / 60);
if($mins <= 1) $since = '1 min';
else $since = sprintf( '%s mins', $mins);
}
else if(($diff <= 86400) && ($diff > 3600))
{
$hours = round($diff / 3600);
if ($hours <= 1) $since = '1 hour';
else $since = sprintf( '%s hours', $hours );
}
elseif ($diff >= 86400)
{
$days = round($diff / 86400);
if ($days <= 1) $since = '1 day';
else $since = sprintf( '%s days', $days );
}
return $since;
}
echo human_time_diff( '1166454231', '2166592806' );
?>