Search code examples
phpstrtotimedate-arithmeticdate-comparison

PHP date comparison giving unintended results


I am formatting dates to American style format mm/dd/yyyy (without time) and comparing the dates but not getting expected results.

echo $startDate ;  // 09/14/2018
echo $nextDate ;   // 03/08/2019
echo $stopDate ;   // 03/08/2019

The above variables are being created in the following fashion:

$nextDate = date('m/d/Y',strtotime("today")) ;

And then comparing dates as:

if ($nextDate >= $startDate && $nextDate <= $stopDate) {
  ...
  do stuff
  ...
}

$nextDate is greater than $startdate and is equal to $stopDate but its not making it inside the IF statement. What am I missing here?


Solution

  • Do it this way with strtotime(),

    $startDate = strtotime($startDate);
    $stopDate= strtotime($stopDate);
    $nextDate =strtotime("today");
    
    if ($nextDate >= $startDate && $nextDate <= $stopDate) {
      ...
      do stuff
      ...
    }
    

    WORKING DEMO: https://3v4l.org/BWZN5