phpdateoopdiff

php DateTime diff return zero


I am just wondering why DateTime::diff returns ZERO. i am expected to return 5 days, definitely i am doing something wrong. somebody here would please correct my code..

$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

Solution

  • $date gets subtracted value (the same value is returned) So $warning & $date has the same value -

    to solve this problem... i just clone the $date variable ;-) and it works

    $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