Display the Difference Between Two Dates in PHP

August 9, 2013 • 1 min read

Here’s a quick function to display the difference between two dates using PHP. The function will return the correct pluralized wording and hide any with zero. For example if the date is less than 1 year, it would hide “0 year” from displaying.

/**
 * Display the difference between two dates
 * (30 years, 9 months, 25 days, 21 hours, 33 minutes, 3 seconds)
 *
 * @param  string $start starting date
 * @param  string $end=false ending date
 * @return string formatted date difference
 */
function dateDiff($start,$end=false)
{
   $return = array();

   try {
      $start = new DateTime($start);
      $end = new DateTime($end);
      $form = $start->diff($end);
   } catch (Exception $e){
      return $e->getMessage();
   }

   $display = array('y'=>'year',
               'm'=>'month',
               'd'=>'day',
               'h'=>'hour',
               'i'=>'minute',
               's'=>'second');
   foreach($display as $key => $value){
      if($form->$key > 0){
         $return[] = $form->$key.' '.($form->$key > 1 ? $value.'s' : $value);
      }
   }

   return implode($return, ', ');
}

// examples
echo dateDiff('1982-10-14'); // 30 years, 9 months, 25 days, 21 hours, 33 minutes, 3 seconds
echo dateDiff('2001-09-05 08:15:05','2002-02-15 04:10:02'); // 5 months, 9 days, 19 hours, 54 minutes, 57 seconds