note 80389 deleted from function.date by derick

From: Date: Wed, 07 May 2008 18:17:01 +0000
Subject: note 80389 deleted from function.date by derick
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-139144@lists.php.net to get a copy of this message
Note Submitter: mariodivece at yahoo dot com ---- Here's an improved version of marius' and june's getWorkingDays function. Basically, it adds floating point precision to the operation allowing you to express the difference any interval you'd like using the day as a conversion base. For example, if you want the difference in hours (which is what I needed), just multiply getWorkingDaysDifference * 24 <?php // Gets the floating point difference in working days between two dates. function getWorkingDays($startDate, $endDate, $holidays){ // Calculate weekday number. Monday is 1, Sunday is 7 $firstWeekdayNumber = date("N", strtotime($startDate)); $lastWeekdayNumber = date("N", strtotime($endDate)); // Normalize the dates if they're weekends or holidays as they count for full days (24 hours) if ($firstWeekdayNumber == 6 || $firstWeekdayNumber == 7 || in_array( date("Y-m-d", strtotime($startDate)), $holidays )) $startDate = date("Y-m-d 00:00:00", strtotime($startDate)); if ($lastWeekdayNumber == 6 || $lastWeekdayNumber == 7 || in_array( date("Y-m-d", strtotime($endDate)), $holidays )) $endDate = date("Y-m-d 00:00:00", strtotime("+1 days", strtotime( $endDate ))); // Compute the floating-point differences in the dates $daysDifference = (strtotime($endDate) - strtotime($startDate)) / 86400; $fullWeeksDifference = floor($daysDifference / 7); $remainingDaysDifference = fmod($daysDifference, 7); // Subtract the weekends; In the first case the whole interval is within a week, in the second case the interval falls in two weeks. if ($firstWeekdayNumber <= $lastWeekdayNumber){ if ($firstWeekdayNumber <= 6 && 6 <= $lastWeekdayNumber && $remainingDaysDifference >= 1) $remainingDaysDifference--; if ($firstWeekdayNumber <= 7 && 7 <= $lastWeekdayNumber && $remainingDaysDifference >= 1) $remainingDaysDifference--; } else{ if ($firstWeekdayNumber <= 6 && $remainingDaysDifference >= 1) $remainingDaysDifference--; // In the case when the interval falls in two weeks, there will be a Sunday for sure $remainingDaysDifference--; } // Compute the working days based on full weeks + $workingDays = $fullWeeksDifference * 5; if ($remainingDaysDifference > 0 ) $workingDays += $remainingDaysDifference; // Subtract the holidays foreach($holidays as $holiday) { $holidayTimeStamp=strtotime($holiday); // If the holiday doesn't fall in weekend if (strtotime($startDate) <= $holidayTimeStamp && $holidayTimeStamp <= strtotime($endDate) && date("N",$holidayTimeStamp) != 6 && date("N",$holidayTimeStamp) != 7 && $workingDays >= 1) $workingDays--; } // End of calculation, return the result now return $workingDays; } ?>

« previous php.notes (#139144) next »