Date Comparisons in PHP – using strtotime()

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.

  1. The formatting – dash(-) separators vs. colon(:) vs. backslash(/)
  2. 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’;