0

php 计算两个给定日期相差天数

方法一:

//关键函数:

//floor() 函数向下舍入为最接近的整数,返回不大于 x 的下一个整数,将 x 的小数部分舍去取整。

//floor() 返回的类型仍然是 float,因为 float 值的范围通常比 integer 要大。


$startdate = date("Y-m-d");
$enddate = "2017-1-11 11:45:09";
$date = floor((strtotime($enddate)-strtotime($startdate))/86400);//一天86400秒

echo "今天与 {$enddate}相差".$date."天";



方法二:

//关键函数:

//getdate(timestamp); 返回当前本地的日期/时间的日期/时间信息。

//round() 函数对浮点数进行四舍五入。

//abs() 函数返回一个数的绝对值。


function count_days($a,$b){
    $a_dt=getdate($a);
    $b_dt=getdate($b);
    $a_begin=mktime(12,0,0,$a_dt['mon'],$a_dt['mday'],$a_dt['year']);     
    $b_end=mktime(12,0,0,$b_dt['mon'],$b_dt['mday'],$b_dt['year']);
    return round(abs($a_begin-$b_end)/3600/24);
}
//今天与2017年1月11日相差多少天
$date1 = strtotime(date("Y-m-d"));
$date2 = strtotime('2017-1-11 11:45:09');
$result = count_days($date1,$date2);

echo "今天与 {$date2}相差".$result."天<br/>";