Search code examples
phpif-statementdatediffphp-5.6

Unable to correctly calculate date with "0000-00-00" date in php


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.

$datediff1 = 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 8
//// If i reverse the date like $datediff1->diff($datediff2);
//// it will return 7 instead

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 ?

SEE IT ONLINE HERE

PS : I am using PHP 5.6


Solution

  • You can rely on the fact that the timestamp starts with 1970 so a 0000 year would result a negative timestamp :

    $date1 = "2018-11-07";
    $date2 = "0000-00-00";
    $datedif1 = new DateTime($date1);
    $datediff2 = new DateTime($date2);
    
    // check if strtotime returns a valid timestamp and the year is not 0000
    $interval = (!strtotime($date1) || 
       !strtotime($date2) || strtotime($date1) < 0 || 
       strtotime($date2) < 0) ? 0 : $date2->diff($date1);
    print_r($interval);
    

    This needs to be refined because it won't work in all cases but it's working in your case.