Date Comparisons in PHP are tricky. The best way to compare dates is by using strtotime()
. My reasoning is simple – keep everything on the same level. Especially when dealing with user input, you don’t know a couple things.
- The formatting – dash(-) separators vs. colon(:) vs. backslash(/)
- The specificity – days, hours, minutes, seconds?
Now you can format these with regex, or PHP splits and joins, to make sure that they meet PHP standards, and then use strtotime – comparing strings will not work in many cases.
{code type=php}
if( strtotime( $date1) > strtotime( $date2 ) ) {
echo ‘$date1 is later than $date2’;
}{/code}