Example #1
0
 public static function diferencia_fechas($fecha_1, $fecha_2)
 {
     if (Date_time::restar_fechas($fecha_1, $fecha_2) < 0) {
         $fecha_inicio_array = explode("-", $fecha_2);
         $fecha_fin_array = explode("-", $fecha_1);
     } else {
         $fecha_inicio_array = explode("-", $fecha_1);
         $fecha_fin_array = explode("-", $fecha_2);
     }
     // configure the base date here
     $base_day = (int) $fecha_inicio_array[2];
     // no leading "0"
     $base_mon = (int) $fecha_inicio_array[1];
     // no leading "0"
     $base_yr = $fecha_inicio_array[0];
     // use 4 digit years!
     // get the current date (today) -- change this if you need a fixed date
     $current_day = (int) $fecha_fin_array[2];
     $current_mon = (int) $fecha_fin_array[1];
     $current_yr = $fecha_fin_array[0];
     // and now .... calculate the difference! :-)
     // overflow is always caused by max days of $base_mon
     // so we need to know how many days $base_mon had
     $base_mon_max = date("t", mktime(0, 0, 0, $base_mon, $base_day, $base_yr));
     // days left till the end of that month
     $base_day_diff = $base_mon_max - $base_day;
     // month left till end of that year
     // substract one to handle overflow correctly
     $base_mon_diff = 12 - $base_mon - 1;
     // start on jan 1st of the next year
     $start_day = 1;
     $start_mon = 1;
     $start_yr = $base_yr + 1;
     // difference to that 1st of jan
     $day_diff = $current_day - $start_day + 1;
     // add today
     $mon_diff = $current_mon - $start_mon + 1;
     // add current month
     $yr_diff = $current_yr - $start_yr;
     // and add the rest of $base_yr
     $day_diff = $day_diff + $base_day_diff;
     $mon_diff = $mon_diff + $base_mon_diff;
     // handle overflow of days
     if ($day_diff >= $base_mon_max) {
         $day_diff = $day_diff - $base_mon_max;
         $mon_diff = $mon_diff + 1;
     }
     // handle overflow of years
     if ($mon_diff >= 12) {
         $mon_diff = $mon_diff - 12;
         $yr_diff = $yr_diff + 1;
     }
     return array("years" => $yr_diff, "months" => $mon_diff, "days" => $day_diff);
 }