Wednesday, October 6, 2010

11:17 PM
2

The date format we are using is “YYYY-MM-DD”, which is the standard format of date value stored in the MySql database.

Function to find the difference of days between two dates

function daysDifference($endDate, $beginDate)
{
   //explode the date by "-" and storing to array
   $date_parts1=explode("-", $beginDate);
   $date_parts2=explode("-", $endDate);
   //gregoriantojd() Converts a Gregorian date to Julian Day Count
   $start_date=gregoriantojd($date_parts1[1], $date_parts1[2], $date_parts1[0]);
   $end_date=gregoriantojd($date_parts2[1], $date_parts2[2], $date_parts2[0]);
   return $end_date - $start_date;
}

The above function is fairly simple, first of all the dates values in the format “YYYY-MM-DD” is separated into array by using explode() function. The first element of array contains the year, the second element contains the month and the last element contains the day value.
And the most import function in finding the days difference is gregoriantojd(), this function converts a Gregorian date to Julian Day Count. This function takes three parameters- month, day and year.
And in the last line of the function, the difference between the Julian Day count of two dates are calculated and returned.

Example :

<?php
   echo daysDifference('2008-03-12','2008-03-09');
?>

What is the output of the above statement, I don’t think I need to write it down. But, I’m a nice guy and never leave the suspense, it’s 3.

2 comments:

Unknown said...

Thanks for the program code. It was really great stuff as difference between dates are always to be asked in our exams :D
php development india

mahesh2010 said...

But some times this code doesn't seem to work properly like it won't show the exact result, Also some times an error screen will appear, ecommerce web developer