Question

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;

}
Was it helpful?

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');

}

OTHER TIPS

Check for $difference->invert

function count_days($start_date, $end_date){

   $d1 = new DateTime($start_date);
   $d2 = new DateTime($end_date);
   $difference = $d1->diff($d2);
   if ($difference->invert == 1) { //if 1 then difference will in minus other wise inplus
      return -$difference->d;
   } else {
     return $difference->d;
   }

}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top