php DateTime diff返回零

时间:2014-09-27 06:31:33

标签: oop

我只是想知道为什么DateTime :: diff返回ZERO。我预计会回来5天,肯定是我做错了。有人在这里请更正我的代码..

$oneYearPlus = str_replace(':', '-', date('Y:m:d', strtotime('+1 year', strtotime('now'))));

var_dump($oneYearPlus);

$date        = new DateTime($oneYearPlus);  ## 2015-09-26

var_dump($date); // Output
--------------------------------
object(DateTime)[18]
  public 'date' => string '2015-09-27 00:00:00' (length=19)
  public 'timezone_type' => int 3
  public 'timezone' => string 'Europe/Moscow' (length=13)
--------------------------------

$warning     =  $date->sub(new DateInterval('P5D')); ## 2014-09-21

var_dump($warning); // Output
--------------------------------
object(DateTime)[18]
  public 'date' => string '2015-09-22 00:00:00' (length=19)
  public 'timezone_type' => int 3
  public 'timezone' => string 'Europe/Moscow' (length=13)
--------------------------------

$interval    =  $warning->diff($date);
var_dump($interval->format('%a days')); ## output 0 days

1 个答案:

答案 0 :(得分:2)

$ date得到减去的值(返回相同的值)所以$ warning& $ date具有相同的值 -

解决这个问题...我只是克隆$ date变量;-)并且它可以正常工作

$oneYearPlus = str_replace(':', '-', date('Y:m:d', strtotime('+1 year', strtotime('now'))));

            var_dump($oneYearPlus);

            $date        = new DateTime($oneYearPlus);  ## 2015-09-26
            var_dump($date);
            $clone = clone $date;

            $warning     =  $date->sub(new DateInterval('P5D')); ## 2014-09-21
            var_dump($warning);

            $interval    =  $warning->diff($clone);
            var_dump($interval->format('%a days')); ## output 0 days