Search code examples
php

Why is Diff always positive when comparing dates?


I'm using this code to return the number of days between two dates - today, and a date from the database:

$now = new DateTime("now");
$date2 = new DateTime($row[$CalendarField]);
$interval = $now->diff($date2);
$age = $interval->days;

How can I alter the code so that $age returns a negative value for dates in the past?


Solution

  • Look at the invert property in DateInterval class.
    http://php.net/manual/en/class.dateinterval.php

    You can also use characters r and R in DateInterval::format method.
    http://php.net/manual/en/dateinterval.format.php

    Try to replace your code with

    
        $now = new DateTime("now");
        $date2 = new DateTime($row[$CalendarField]);
        $interval = $now->diff($date2);
        $age = $interval->format('%r%a');