0

I want to find the total number of specific days between two dates. I need a proper solution for future usage, I want to use any start date and end date in the future.

My Code

$start_date       = new DateTime('2020/10/01');
$end_date         = new DateTime('2020/10/31'); 
$days = array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday');
$diff = $start_date->diff($end_date, true)->days;
foreach ($days as $key => $value) {
   $number_of_days = intval($diff / 7) + ($start_date->format('N') + $diff % 7 >= $key+1);
   $result[$value] = $number_of_days;
}

result

Array
(
    [Monday] => 5
    [Tuesday] => 5
    [Wednesday] => 5
    [Thursday] => 5
    [Friday] => 5
    [Saturday] => 5
    [Sunday] => 5
)

Expecting Result

Array
(
    [Monday] => 4
    [Tuesday] => 4
    [Wednesday] => 4
    [Thursday] => 5
    [Friday] => 5
    [Saturday] => 5
    [Sunday] => 4
)

2 Answers2

2

Please check next solution:

<?php
// create DateTime objects for date start & date end
$start_date       = new DateTime('2020/11/01');
$end_date         = new DateTime('2020/11/31'); 

// initialize counter array fro each day of week
$res = array(
    'Monday'   => 0,
    'Tuesday'  => 0,
    'Wednesday'=> 0,
    'Thursday' => 0,
    'Friday'   => 0,
    'Saturday' => 0,
    'Sunday'   => 0
);

// iterate dates between $start_date & $end_date
// if $end_date should not be included '<=' should be changed to '<'
while ($start_date <= $end_date) {
    $week_day = $start_date->format('l'); // get weekday for each date in interval
    $res[$week_day]++;                    // increase weekday counter
    $start_date->add(new DateInterval('P1D')); // iterate next day
}

print_r($res);

Here live code PHPize.online

Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39
-2

First of all: The week starts with Sunday.

    $weekDays = ['Sunday', ...];

Then do not do something in a loop that is not dependend on the loop value:

$numberOfDays = intval($diff / 7);
foreach ($weekDays as $weekDay) {
    $result[$weekDay] = $numberOfDays;
}
for ($weekDay = $startDate->format('N'), $endWeekDay = $endDate->format('N'); $weekDay != $endWeekday; $weekDay = ($weekDay + 1) % 7){
    $result[$weekday]++;
}

Answer might change a bit depending on whether you want to include the start and end date.

Adam P.
  • 108
  • 5
  • 1
    "The week starts with Sunday" - what do you mean by that? According to ISO 8601, monday is the first day of the week, which is consensus in most western countries – Nico Haase Oct 01 '20 at 12:14