在放代码之前,我得先说一下,无论是计算2016-08-01到2017-08-01的时间差,还是2017-08-01到2016-08-01的时间差,返回的都将是365天,不会出现正负数的情况,请知悉!下面上代码:
/** * PHP计算两个时间差的方法一 * ======== 实例使用 ======== * $timediff = timeDiff( strtotime( "2016-07-07" ), strtotime( "2016-07-01" ) ); * 返回:天-时-分-秒 */ function timeDiff( $begin_time, $end_time ){ if ( $begin_time < $end_time ) { $starttime = $begin_time; $endtime = $end_time; } else { $starttime = $end_time; $endtime = $begin_time; } $timediff = $endtime - $starttime; $days = intval( $timediff / 86400 ); $remain = $timediff % 86400; $hours = intval( $remain / 3600 ); $remain = $remain % 3600; $mins = intval( $remain / 60 ); $secs = $remain % 60; $res = array( "day" => $days, "hour" => $hours, "min" => $mins, "sec" => $secs ); return $res; } /** * PHP计算两个时间差的方法二 * ======== 实例使用 ======== * $timediff = timeDiff( strtotime( "2016-07-07" ), strtotime( "2016-07-01" ) ); * 返回:年-月-日-时-分-秒 */ function dateDiff( $begin_time, $end_time ){ if ( $begin_time < $end_time ) { $starttime = $begin_time; $endtime = $end_time; } else { $starttime = $end_time; $endtime = $begin_time; } $timediff = $endtime - $starttime; $year = intval($timediff / 31536000); $remain = $timediff % 31536000; $month = intval( $remain / 2592000 ); $remain = $timediff % 2592000; $days = intval( $remain / 86400 ); $remain = $timediff % 86400; $hours = intval( $remain / 3600 ); $remain = $remain % 3600; $mins = intval( $remain / 60 ); $secs = $remain % 60; $res = array( "year"=>$year,"month"=>$month, "day" => $days, "hour" => $hours, "min" => $mins, "sec" => $secs ); return $res; }
有了这个,你就可以得到你想要的时间差咯~
补充一个更简单的方法,PHP原生代码,能够回避时间戳1970的问题:
/** * 比较两个日期 * @param $start_date * @param $end_date * @return array */ function _diff_date($start_date, $end_date) { /** * 回避时间戳1970的问题 */ $datetime_start = new DateTime($start_date); $datetime_end = new DateTime($end_date); return $DateInterval = (array) $datetime_start->diff($datetime_end); } //举个例子,打印结果: print_r(_diff_date('2018-6-11 09:00:00', '2018-6-12 09:00:00'));
结果如下:
Array ( [y] => 0 [m] => 0 [d] => 1 [h] => 0 [i] => 0 [s] => 0 [f] => 0 [weekday] => 0 [weekday_behavior] => 0 [first_last_day_of] => 0 [invert] => 0 [days] => 1 [special_type] => 0 [special_amount] => 0 [have_weekday_relative] => 0 [have_special_relative] => 0 ) [Finished in 0.1s]
没有难的技术,当你弄清它的原理时,你会发现原来如此简单~ 欢迎加群【536501561】讨论