Get date difference between two dates in php

While working with php scripts at some point we need to find out the difference between two specified dates for some purpose.

Here a simple php function does the same. It takes two parameters. Previous and Current date and returns an array with total years, months and days value. If you don't pass the second parameter current date is treated as second parameter.

So you can omit the second parameter to get the difference from current date.


 function date_difference($prev,$cur=''){

  if($cur==''){
   $cur=date('m/d/Y');
   }

  $cd= strtotime(trim($cur));
  $pd= strtotime(trim($prev));

  $diff=$cd-$pd;

  $years = floor($diff / (365*60*60*24));
  $months=floor(($diff-$years*365*60*60*24)/(30*60*60*24));
  $days = floor(($diff - $years * 365*60*60*24 - 
  $months*30*60*60*24) / (60*60*24));

 $ar=array("years"=>$years,"months"=>$months,"days"=>$days);
  return $ar;
 }


Call function like this

$pd='12/15/2010'; //Previous date
$cd=date('m/d/Y'); // Current date
$diff=date_difference($pd,$cd); //Get the difference
print_r($diff); // Print the array
Get date difference between two dates in php Get date difference between two dates in php Reviewed by Altaf Hussain on 8:40 PM Rating: 5

No comments:

Altaf Web. Powered by Blogger.