Home > front end >  How to compare two months (ie, strings) using comparison operator >=
How to compare two months (ie, strings) using comparison operator >=

Time:12-03

     $month = date('F');
     if ($month >= 'June')
     {
          echo true;
     }
     else
     {
          echo false;
     }

The if block is not evaluating at all. I am not getting any result.

CodePudding user response:

To compare two months using the comparison operator >=, you can use the DateTime class and its createFromFormat() method to create DateTime objects for each month. Then, you can use the diff() method to compare the two dates and check if the difference is greater than or equal to 0.

For example:

$month = date('F');
$june = DateTime::createFromFormat('F', 'June');
$currentMonth = DateTime::createFromFormat('F', $month);

$difference = $currentMonth->diff($june);
if ($difference->invert >= 0) {
    echo true;
} else {
    echo false;
}

Note that this code assumes that the current month is after June (i.e. July, August, etc.). If you want to compare the current month to June and include June as well, you can use the greater than or equal to operator ( >= ) instead of the greater than operator ( > ).

  • Related