Compare 2 DateTime variables in PHP and check which one is greater

If you needed to compare 2 DateTime fields in mySQL then you can easily do that in SQL and fetch the correct record however when it comes to PHP you need to use a couple of functions to arrive to the correct answer.

We will used strtotime function which will convert the input DateTime values into its equivalent Unix timesteamp and then perform the comparison. Check out the code below

$date1 = ‘2024-05-22’;
$date2 = ‘2024-08-05’;

if (strtotime($date1) < strtotime($date2)) {
echo ‘Date 1 is before Date 2’;
}
else if (strtotime($date1) > strtotime($date2)) {
echo ‘Date 1 is after Date 2’;
} else {
echo ‘Date 1 and Date 2 are equal’;
}

Hope the above helped

Leave a Reply

Your email address will not be published. Required fields are marked *