function diff_date($date1, $date2){ if($date1>$date2){ $startTime = strtotime($date1); $endTime = strtotime($date2); }else{ $startTime = strtotime($date2); $endTime = strtotime($date1); } $diff = $startTime-$endTime; $day = $diff/86400; return intval($day);}
测试结果:
$date1 = '2017-03-15 00:00:00';$date2 = '2017-03-16 00:00:00';echo diff_date($date1,$date2);//输出:1 $date1 = '2017-03-15 00:00:01';$date2 = '2017-03-16 00:00:00';echo diff_date($date1,$date2);//输出:0 $date1 = '2017-03-15 00:00:01';$date2 = '2017-03-16 00:00:02';echo diff_date($date1,$date2);//输出:0
总结
此方法为24小时制,也就是说时间必须满24小时才算一天
此方法和上面的类似,只不过是传入的参数直接是时间戳
function diff_time($time1,$time2){ if($time1 < $time2){ $time0 = $time1; $time1 = $time2; $time2 = $time0; } $diff = ($time1-$time2)/86400; return intval($diff);}
附加学习
PHP中计算两个时间相差的天数、小时数、分钟数、秒数不如其它语言方便,但搞清了PHP中时间的表示方法后也很简单。本文章向大家讲解php如何计算时间相差。需要的码农可以参考一下
$date1 = '2017-03-15 00:00:01';$date2 = '2017-03-15 00:00:00'; $date=floor((strtotime($date1)-strtotime($date2))/86400);echo "相差天数:".$date."天"; $hour=floor((strtotime($date1)-strtotime($date2))%86400/3600);echo "相差小时数:".$hour."小时"; $minute=floor((strtotime($date1)-strtotime($date2))%86400/60);echo "相差分钟数:".$minute."分钟"; $second=floor((strtotime($date1)-strtotime($date2))%86400%60);echo "相差秒数:".$second."秒"; //输出://相差天数:0天//相差小时数:0小时//相差分钟数:0分钟//相差秒数:1秒
来源地址:https://blog.csdn.net/qq_37448303/article/details/126738169