How to calculate days per month with start date and duration?

Trying to figure out a little problem. I have a start date and duration (in weeks), and you need to calculate the number of working days per month for the duration.

For example: Start date: 2011-02-07 Duration: 10 weeks

I would like to get the following:

February: 16 days March: 23 days April: 11 days

Any help would be great. Thank you

+3
source share
2 answers

Pre 5.3 Solution:

$start = $current = strtotime('2011-02-07');
$end = strtotime('+10 weeks', $start);
$months = array();
while($current < $end) {
    $month = date('M', $current);
    if (!isset($months[$month])) {
        $months[$month] = 0;
    }
    $months[$month]++;
    $current = strtotime('+1 weekday', $current);
}
print_r($months);

Output ( codepad ):

Array
(
    [Feb] => 16
    [Mar] => 23
    [Apr] => 11
)
+4
source
$start=date_create('2011-02-07');
$interval=new DateInterval('P10W');
$end=date_add(clone $start,$interval);//use clone otherwise $start gets changed

$period=new DatePeriod($start, new DateInterval('P1D'), $end);

foreach($period as $day){
  if($day->format('N')<6) $workdays[$day->format('F')]++; //N is 1-7 where Monday=1
}

var_dump($workdays);
+3
source

Source: https://habr.com/ru/post/1784986/


All Articles