Skip to content

Instantly share code, notes, and snippets.

@jacobwyke
Created January 24, 2013 14:54
Show Gist options
  • Save jacobwyke/4622583 to your computer and use it in GitHub Desktop.
Save jacobwyke/4622583 to your computer and use it in GitHub Desktop.
PHP code to work out the number of weekdays between two DateTime objects.
/**
* Weekdays between dates
*
* Works out the number of weekdays between two dates.
* @param DateTime $objStartDate The start date
* @param DateTime $objEndDate The end date
* @return int The number of weekdays or -1 if end date is before start date.
*/
function weekdaysBetweenDates(DateTime $objStartDate, DateTime $objEndDate){
//set the time of the day to the same values since we only care about days
$objStartDate->setTime(0, 0, 0);
$objEndDate->setTime(0, 0, 0);
//ensure the end date is not before the start date
if($objStartDate<=$objEndDate){
$numDays = 0;
while($objStartDate<$objEndDate){
if($objStartDate->format('N')<6){
$numDays++;
}
$objStartDate->add(new DateInterval('P1D'));
}
return $numDays;
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment