mardi 6 novembre 2018

How to prevent calculate between two dates when there is a null date from one it?

I have two date like this

$date1 = "2018-11-07"; 
$date2 = "2018-11-12";

I want to compare these two date so i could get a range of day between these date. I used DiffDate function. It's looks like below syntax.

$datedif1 = new DateTime($date1);
$datediff2 = new DateTime($date2);
$interval = $datediff2->diff($datediff1);
echo $interval->d;   // will return 5

I got the function, but i have problem when one from these two date had a value like "0000-00-00". They started to looks like this.

$date1 = "2018-11-07";
$date2 = "0000-00-00";
$datedif1 = new DateTime($date1);
$datediff2 = new DateTime($date2);
$interval = $datediff2->diff($datediff1);
echo $interval->d;   // will return 7

My question is how could i prevent these two dates return 0 when one or all dates have "0000-00-00" value ? I have tried like using if...else....

if($date1 == "0000-00-00" || $date2 == "0000-00-00"){
  $interval = "0";
  echo $interval;
}else {
  $interval = $date2->diff($date1);
  $i = $interval->d;

}

Is there any better way to do it rather than using if else statement ?

Aucun commentaire:

Enregistrer un commentaire