Skip to content


Number of Working Days between two Dates

This sections will contains code regarding different PHP & MySQL features and contains help about php/mysql issues.

Number of Working Days between two Dates

Postby php developer » May 29th, 2009, 5:53 am

Sometimes you may need to calculate the number of working days between two dates. The below code enables you to calculate the number of days between two dates and number of working days between two dates assuming 5 days a week as working days.

Number of Days between two Dates:
Code: Select all
function getDays($sStartDate, $sEndDate)
{
    //The total number of days between the two dates. We compute the no. of seconds and divide it to 60*60*24
    $fDays = (abs(strtotime($sEndDate) - strtotime($sStartDate)) / 86400);

    return @ceil($fDays);
}


Number of Working Days between two Dates:
Code: Select all
function getWorkingDays($sStartDate, $sEndDate)
{
   // The total number of days between the two dates. We compute the no. of seconds and divide it to 60*60*24
   $fDays = (abs(strtotime($sEndDate) - strtotime($sStartDate)) / 86400);

   $iFullWeeks         = @floor($fDays / 7);
   $iWeekRemainingDays = @fmod($fDays, 7);

   // It will return 1 if it's Monday,.. ,7 for Sunday
   $iWeekFirstDay = date("N", strtotime($sStartDate));
   $iWeekLastDay  = date("N", strtotime($sEndDate));

   // The two can be equal in leap years when february has 29 days, the equal sign is added here
   // In the first case the whole interval is within a week, in the second case the interval falls in two weeks.
   if ($iWeekFirstDay <= $iWeekLastDay)
   {
      if ($iWeekFirstDay <= 6 && 6 <= $iWeekLastDay)
         $iWeekRemainingDays --;

      if ($iWeekFirstDay <= 7 && 7 <= $iWeekLastDay)
         $iWeekRemainingDays --;
   }

   else
   {
      if ($iWeekFirstDay <= 6)
      {
         // In the case when the interval falls in two weeks, there will be a Sunday for sure
         $iWeekRemainingDays --;
      }
   }

   // The no. of business days is: (number of weeks between the two dates) * (5 working days) + the remainder
   // february in none leap years gave a remainder of 0 but still calculated weekends between first and last day, this is one way to fix it
   $fWorkingDays = $iFullWeeks * 5;

   if ($iWeekRemainingDays > 0)
     $fWorkingDays += $iWeekRemainingDays;

   return @ceil($fWorkingDays);
}


Note: The use the following date format YYYY-MM-DD.
User avatar
php developer
 
Posts: 53
Joined: July 25th, 2008, 4:56 am

Return to Board index

Return to PHP / MySQL / XML

Who is online

Users browsing this forum: No registered users and 0 guests