Search code examples
phpdatetimedateinterval

DateTime class how to deal with negative date interval


I have a simple function that returns the number of days between two dates using the DateTime diff function. But right now it still returns a positive number if the end date is before the start date. Is there a way to return a negative difference using this method? Or would I bet better just to check with strtotime first in my function? Ideally I think I will just return 0 of its a negative difference.

//Returns the total number of days between two dates
function count_days($start_date, $end_date){

    $d1 = new DateTime($start_date);
    $d2 = new DateTime($end_date);
    $difference = $d1->diff($d2);
    return $difference->days;

}

Solution

  • Use the r flag to get the negative sign in there:

    function count_days($start_date, $end_date){
    
        $d1 = new DateTime($start_date);
        $d2 = new DateTime($end_date);
        $difference = $d1->diff($d2);
        return $difference->format('%r%a days');
    
    }