Compare Two Dates in PHP

Description: A function to compare two dates for equality. The dates are expected to be valid and parsable by strtotime() function. It returns your typical -1, 0, 1 value for equality.
Tested Platform: PHP 7+
Language: PHP
// Compare two dates for equality
// Expects: Two correctly formatted dates recognized by strtotime
// Returns: -1 if date 1 is before date 2, 0 if equal, 1 if date 1 is after.

function compareDates($date1, $date2) {
     if (empty($date1)) { return -1; }
     if (empty($date2)) { return 1; }
        
     $dt1 = strtotime($date1);
     $dt2 = strtotime($date2);
        
     if ($dt1 === false) { return -1; }
     if ($dt2 === false) { return 1; }
        
     if ($dt1 == $dt2) { return 0; }
     else {
          return ($dt1 > $dt2) ? 1 : -1;
     }
}

Posted: March 18, 2023

Return to the snippets listing