DateCompare

The DateCompare function has been a very useful tool when building reports. By default, this function will compare dates down to the second. With a little bit of tweaking, you can have it compare down to the nano second. By sending a datepart in, you can specify the level of percision that you want.
Parameter Description
date1 Date/time object, in the range 100 AD–9999 AD.
date2 Date/time object, in the range 100 AD–9999 AD.
datePart Optional. String. Precision of the comparison. s Precise to the second (default) n Precise to the minute h Precise to the hour d Precise to the day m Precise to the month yyyy Precise to the year

 

 <?php

    function DateCompare($date1, $date2=date("Y-m-d H:i:s"), $datepart)
    {
         $a = explode(" ",$date1);
         $b = explode("-",$a[ 0]);
         if(count($a) > 1)
         {
              $c = explode(":",$a[ 1]);
         } 
         else
         {
              $c = array();$c[0] = 0;$c[1] = 0;$c[2] = 0;
         }
         $a1 = explode(" ",$date2);
         $b1 = explode("-",$a1[0]);    
         if(count($a1) > 1)
         {
            $c1 = explode(":",$a1[1]);
          } 

          else
         {
              $c1 = array();$c1[0] = 0;$c1[1] = 0;$c1[2] = 0;
         }
         switch($datepart)
         {
              case "n": // Minute
                   $c[0] = 0;$c1[0] = 0;break;
              case "h": // Hour
                   $c[0] = 0;$c[1] =0;$c1[0] = 0;$c1[1] = 0;break;
             case "d": // Day
                   $c[ 0] = 0;$c[1] = 0;$c[2] = 0;$c1[ 0] = 0;$c1[1] = 0;$c1[2] = 0;break;
               case "m": // Month
                   $c[0] = 0;$c[ 1] = 0;$c[2] = 0;$c1[0] = 0;$c1[ 1] = 0;$c1[2] = 0;$b[1] = 0;$b1[1] = 0;break;
              case "yyyy": // Year
                   $c[ 0] = 0;$c[1] = 0;$c[2] = 0;$c1[0] = 0;$c1[1] = 0;$c1[2] = 0;$b[1] = 0;$b1[ 1] = 0;$b[2] = 0;$b1[3] = 0;break;
               default:
                   $e = "mc2";
         }
         $nDate1 = mktime($c[0 ],$c[1],$c[2],$b[1],$b[2],$b[0]);
         $nDate2 = mktime($c1[0],$c1[1],$c1[2],$b1[1],$b1[2],$b1[0 ]);
         if($nDate1 < $nDate2)
         {
              return -1;
         }
         elseif ($nDate1 > $nDate2)
         {
              return 1;
         }
         else
         {
               return 0;
         }
    }

?>
 

Usage:
Using the DateCompare function is easy.  If date 1 is greater than date 2, the function will return 1.  If date 1 is less than date 2, the function will return a -1.  If the two dates are equal, the function will return a 0.

<?php
    $date1 = "2007-05-01 15:07:54" ;
    $date2 = "2007-06-07 02:41:22";
    if(DateCompare($date1,$date2) == 1)
    {
         echo "Date 1 is GREATER THAN Date 2";
    }
    elseif (DateCompare($date1,$date2) == -1)
    {
         echo "Date 1 is LESS THAN Date 2";
    }
    else
    {
        echo "Date 1 EQUALS Date 2" ;
    }
?>