PHP的DateTime :: Diff"窃取"一天

jur*_*pro 3 php datetime

我想计算两天之间的日期差异.问题是,当我计算天数时,计算中缺少一天(当天).

可以说date1是20-12-2014,date2是21-12-2014.使用这两个日期的DateTime :: Diff的结果为0(我想成为1,而不是零)

我错过了什么不好或DateTime :: Diff计算日期差异像我上面解释的那样?

这是我正在使用的代码(我希望以天显示日期差异):

      $currentDay = new DateTime();
        $listDay = new DateTime($results["date"]);//from mysql database (output is like 21-12-2014
        $interval = $currentDay->diff($listDay);
        $daysLeft=(int)$interval->format("%r%a");
Run Code Online (Sandbox Code Playgroud)

Gla*_*vić 6

就像@Matt在评论中已经说过的那样,你不仅要比较日期,还要比较日期和时间,$currentDay变量中的时间设置为当前时间,时间$listDay设置为00:00:00.你可以快速看到,如果你转储这两个变量,比如print_r($currentDay);print_r($listDay);.

解决方案是创建$currentDay时间设置为的DateTime对象00:00:00,这可以通过today关键字轻松完成:

$currentDay = new DateTime('today');
$listDay = new DateTime($results['date']);
$interval = $currentDay->diff($listDay);
echo $interval->format('%r%a');
Run Code Online (Sandbox Code Playgroud)

demo