How to compare two dates in PHP
In this tutorial, we will learn how to compare two dates in PHP.
Example 1: If the dates are in the same format, then we will use a comparison operator.
1 2 3 4 5 6 7 8 9 |
<?php $date1 = "2022-01-01"; $date2 = "2022-06-29"; if ($date1 < $date2) { echo "$date1 is less than $date2"; else{ echo "$date1 is greater than $date2"; } ?> |
Output: 2022-01-01 is less than 2022-06-29
Example 2: If both dates are in different formats then use strtotime()
the function to convert the given dates into the corresponding timestamp format. After that compare using the comparison operator.
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php $date1 = "2022-01-01"; $date2 = "2022-06-29"; $timestamp1 = strtotime($date1); $timestamp2 = strtotime($date2); if ($timestamp1 > $timestamp2){ echo "$date1 is greater than $date2"; } else{ echo "$date1 is less than $date2"; } ?> |
Output: 2022-01-01 is less than 2022-06-29