一聚教程网:一个值得你收藏的教程网站

热门教程

PHP计算两个时间差的例子

时间:2022-06-24 17:22:56 编辑:袖梨 来源:一聚教程网

例子1

 代码如下 复制代码

//$startdate是开始时间,$enddate是结束时间

$startdate="2011-3-15 11:50:00";
$enddate="2012-12-12 12:12:12";
$date=floor((strtotime($enddate)-strtotime($startdate))/86400);
$hour=floor((strtotime($enddate)-strtotime($startdate))%86400/3600);
$minute=floor((strtotime($enddate)-strtotime($startdate))%86400/60);
$second=floor((strtotime($enddate)-strtotime($startdate))%86400%60);
echo $date."天
";
echo $hour."小时
";
echo $minute."分钟
";
echo $second."秒
";
 ?>

例子2

 代码如下 复制代码

$one = strtotime('2011-05-08 07:02:40');//开始时间 时间戳
$tow = strtotime('2012-12-25 00:00:00');//结束时间 时间戳
$cle = $tow - $one; //得出时间戳差值

/* 这个只是提示
echo ceil($cle/60); //得出一共多少分钟
echo ceil($cle/3600); //得出一共多少小时
echo ceil($cle/3600/24); //得出一共多少天
*/
/*ceil()函数,即进一法取整*/
$d = cell($cle/3600/24);
$h = cell(($cle%(3600*24))/3600);  //%取余
$m = cell(($cle%(3600*24))/60);

echo "两个时间相差 $d 天 $h 小时 $m 分"
?>

总结,两个例子都使用到了strtotime函数把日期转换在时间戳之后再除以86400等操作来算出两个日期之间相差多少时间,从天数据到秒都计算机出来了。

热门栏目