Created
October 16, 2017 03:48
-
-
Save andygock/4be9570ee7f56d7a80f6ac01d59cebc4 to your computer and use it in GitHub Desktop.
PHP: Calculate number of weekdays between two dates.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Calculate number of weekdays between two dates. | |
* | |
* @param string $from Start date, in format "YYYY-MM-DD" | |
* @param string $to End datem in format "YYYY-MM-DD" | |
* @return int|null Number of weekdays between $from and $to. NULL if either $from or $to is NULL. | |
*/ | |
static function date_diff_weekdays($from, $to) { | |
if ($from === null || $to === null) | |
return null; | |
$date_from = new DateTime($from); | |
$date_to = new DateTime($to); | |
// calculate number of weekdays from start of week - start date | |
$from_day = intval($date_from->format('w')); // 0 (for Sunday) through 6 (for Saturday) | |
if ($from_day == 0) | |
$from_day = 7; | |
$from_wdays = $from_day > 5 ? 5 : $from_day; | |
// calculate number of weekdays from start of week - end date | |
$to_day = intval($date_to->format('w')); | |
if ($to_day == 0) | |
$to_day = 7; | |
$to_wdays = $to_day > 5 ? 5 : $to_day; | |
// calculate number of days between the two dates | |
$interval = $date_from->diff($date_to); | |
$days = intval($interval->format('%R%a')); // shows negative values too | |
// calculate number of full weeks between the two dates | |
$weeks_between = floor($days / 7); | |
if ($to_day >= $from_day) | |
$weeks_between -= 1; | |
// complete calculation of number of working days between | |
$diff_wd = 5 * ($weeks_between) + (5 - $from_wdays) + $to_wdays; | |
return $diff_wd; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This doesn't work properly.