PHP面试题中,关于日期的题目作为基础考题经常出现,下面讨论一下获取两个日期之间的天数的方法。
收到一个答案,拆分年、月、日,分别进行减法,然后统计天数,好累。
针对低版本的PHP可以用下面的方式搞定:
$date1 = '2014-02-18 00:09:13';
$date2 = '2014-03-19 00:02:18';
function differDays($date1, $date2) {
$differNums = strtotime($date2) - strtotime($date1);
$differNums = $differNums / (3600 * 24);
echo floor(abs($differNums));
}
echo differDays($date1, $date2);
echo "\n";
//或者
function difDays($date1,$date2){
$date1 = substr($date1, 0, 10);
$date2 = substr($date2, 0, 10);
$time1 = explode("-", $date1);
$time2 = explode("-", $date2);
$date1 = mktime(0, 0, 0, $time1[1],$time1[2],$time1[0]);
$date2 = mktime(0, 0, 0, $time2[1],$time2[2],$time2[0]);
return ($date2 - $date1)/(3600*24) - 1;
}
echo difDays($date1, $date2);
PHP5.3以上版本可以使用date_diff:
function dateDiff($date1, $date2) {
$datetime1 = new DateTime($date1);
$datetime2 = new DateTime($date2);
$interval = $datetime1->diff($datetime2);
return $interval->format('%a');
}
echo dateDiff($date1, $date2);
本文例子下载:http://pan.baidu.com/s/1eQ1Nn14