Aug 06

<?php
//get current month for example
$beginday=date(“Y-m-01”);
$lastday=date(“Y-m-t”);

$nr_work_days = getWorkingDays($beginday,$lastday);
echo $nr_work_days;

function getWorkingDays($startDate, $endDate){
 $begin=strtotime($startDate);
 $end=strtotime($endDate);
 if($begin>$end){
  echo “startdate is in the future! <br />”;
  return 0;
 }else{
   $no_days=0;
   $weekends=0;
  while($begin<=$end){
    $no_days++; // no of days in the given interval
    $what_day=date(“N”,$begin);
     if($what_day>5) { // 6 and 7 are weekend days
          $weekends++;
     };
    $begin+=86400; // +1 day
  };
  $working_days=$no_days-$weekends;
  return $working_days;
 }
}
?>

written by MG \\ tags: , ,


9 Responses to “PHP: How to calculate number of work days between 2 dates”

  1. 1. KC Says:

    Thanks a lot for the sharing, Mugurel.
    The solution is the simplest and clearest one on the PHP world.

  2. 2. James Says:

    Thanks for this, helped me to build my own (I’m adding in public holidays). But cant you just do:

    if($what_day<=5) { // 6 and 7 are weekend days
    $working_days++;
    };

    Rather than working which are weekends?

  3. 3. Jeff Says:

    Technically, I think it is quicker to check for 6/7, because the ‘if’ only fires 2 out of 7 times instead of 5 out of 7 times. <-Behold the nit-pickiness 🙂

    Jeff

  4. 4. dootzky Says:

    this actually works! 🙂
    awesome!

    thanks for the code snippet!

  5. 5. Mike Says:

    Really great work, racked my brains until I came across this beauty. Thanks agian

  6. 6. Per Persson Says:

    A loop? Haven’t you ever heard about primitive functions for calculating integrals?

  7. 7. Kevin Says:

    My two cents:

    function workDaysBetweenDates(DateTime $date1, DateTime $date2)
    {
    $workdays = 0;
    $differenceInDays = $date1->diff($date2)->d;

    for ($i = 1; $i <= $differenceInDays; $i++) {
    $dayOftheWeek = date('N', strtotime("+{$i} days"));

    if ($dayOftheWeek <= 5) {
    $add = 6 – $dayOftheWeek;
    $workdays += $add;
    $i += $add + 1;
    }
    }

    return $workdays;
    }

    This only fires once a week unless the starting date is on a saturday, then it will fire two times for the first week.

  8. 8. Shiva Johari Says:

    hey,

    i have a table of company holidays with just two columns, date and occasion. I want to get the no. of working days keeping this table also in mind along with saturdays and sundays

    please help me out

  9. 9. ramu Says:

    given top getWorkingDays working like charm.

    i need one help.

    i am passing array like public holidays list,
    then exclude the public holiday then return the count of working days.

Leave a Reply

*