質問

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;

}
役に立ちましたか?

解決

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

}

他のヒント

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;
   }

}

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top