Home » » Get date difference between two dates in php

Get date difference between two dates in php

Written By Unknown on Jumat, 24 Februari 2012 | 07.10

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
Share this article :

Posting Komentar

 
Support : Creating Website | Johny Template | Mas Template
Copyright © 2011. Kumpulan Kata Broadcast Blackberry - All Rights Reserved
Template Created by Creating Website Published by Mas Template
Proudly powered by Blogger