Reputation: 6370
I'm using this answer to help me but need to work it into my question.
I want to count the days between two dates but then remove the weekends. How can I combine the following two answers?
Date 1 is 06.10.2017 and date 2 is 09.10.2017.
$date1 = new DateTime(get_sub_field('start_date'));
$date2 = new DateTime(get_sub_field('end_date'));
$diff = $date2->diff($date1)->format("%a");
echo $diff;
That gives 3 days. I want it to show 1 as there's a weekend in there. So I need to combine it with the following:
This next answer removes all weekends:
function countDays($year, $month, $ignore) {
$count = 0;
$counter = mktime(0, 0, 0, $month, 1, $year);
while (date("n", $counter) == $month) {
if (in_array(date("w", $counter), $ignore) == false) {
$count++;
}
$counter = strtotime("+1 day", $counter);
}
return $count;
}
echo countDays(2017, 10, array(0, 6)); // 22
Giving 22 business days in Oct.
How can I combine the two answers to show me a count of days between two dates but removing weekends?
Upvotes: 3
Views: 1655
Reputation: 32270
The PHP date and time classes are very powerful.
I'd use DateInterval
and DatePeriod
.
$start = new DateTime('2017-10-06');
$end = new DateTime('2017-10-09');
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($start, $interval, $end);
$businessDays = 0;
foreach ($period as $day) {
// $day is not saturday nor sunday
if (! in_array($day->format('w'), [0, 6])) {
$businessDays++;
}
}
echo $businessDays; // prints 1
Upvotes: 5