php - get number of each day of week between two dates

510

I need to get the number of days for each day of the week between two dates like:

2013-01-01 to 2013-01-15

Mo:2
Tu:3
We:2
Th:2
Fr:2
Sa:2
Su:2

I had this code not sure where I got it before but it seemed to be working but realized theres some date ranges it does not work on like 2013-03-01 to 2013-03-11 it reports Monday as 1 day instead of 2 days.

function daysOfWeekBetween($start_date, $end_date, $weekDay)
{
   $first_date = strtotime($start_date." -1 days");
   $first_date = strtotime(date("M d Y",$first_date)." next ".$weekDay);

   $last_date = strtotime($end_date." +1 days");
   $last_date = strtotime(date("M d Y",$last_date)." last ".$weekDay);

   return  floor(($last_date - $first_date)/(7*86400)) + 1;
}

daysOfWeekBetween($date_range['start_date'], $date_range['end_date'], 'Monday');
959

Answer

Solution:

Came up with a solution:

    $interval = DateInterval::createFromDateString('1 day');
    $begin = new DateTime($date_range['start_date']);
    $end = new DateTime($date_range['end_date']);
    $period = new DatePeriod($begin, $interval, $end);
    foreach($period as $dt)
    {
        $inner_data['average_days_counter'][$dt->format('D')] = isset($inner_data['average_days_counter'][$dt->format('D')]) ? $inner_data['average_days_counter'][$dt->format('D')] + 1 : 1;
    }
    // Array ( [Mon] => 2 [Tue] => 1 [Wed] => 1 [Thu] => 1 [Fri] => 2 [Sat] => 2 [Sun] => 2 ) 

People are also looking for solutions to the problem: php - How to display message from contact form on the main page

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.