Monday, March 9, 2009

Calculating difference between two dates in PHP

In php we need to calculate the difference between the days. For example, In a form we have provided user to enter the two date where we need to calculate the difference between the two dates.

$date1="07/11/2007";

$date2="09/04/2009";

Here we will be calculating the how many days are there in between the above dates.

Php code :

$date1="07/11/2007";

$date2="09/04/2009";

print "If we minus " . $date1 . " from " . $date2 . " we get " . dateDiff("/", $date2, $date1) . ".";

function dateDiff($dformat, $endDate, $beginDate)
{
$date_parts1=explode($dformat, $beginDate);
$date_parts2=explode($dformat, $endDate);
$start_date=gregoriantojd($date_parts1[0], $date_parts1[1], $date_parts1[2]);
$end_date=gregoriantojd($date_parts2[0], $date_parts2[1], $date_parts2[2]);
return $end_date - $start_date;
}

The dateDiff() functions uses two PHP functions viz., explode() and gregoriantojd(). The explode() function is used mostly to convert strings into arrays.

gregoriantojd(): It changes the date into a big number from which another number (obtained from another date) can be deducted.

0 comments:

Post a Comment