Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to find number of mondays or tuesdays between two dates?

Tags:

date

php

I have start date and end date.

I need to find out the day that is Sunday or Monday etc dependent upon user click on check box.

How can I find/calculate that in PHP?

like image 985
svk Avatar asked Oct 31 '09 09:10

svk


People also ask

How do you count Monday Tuesday in Excel?

To apply the SUMPRODUCT function for counting the weekdays we need to follow these steps: Select cell G3 and click on it. Insert the formula: =SUMPRODUCT(--(WEEKDAY(Date,2)=F3)) Press enter.


2 Answers

This question is just crying out for an updated answer that uses PHP's DateTime classes, so here it is:-

/**
 * @param String $dayName eg 'Mon', 'Tue' etc
 * @param DateTimeInterface $start
 * @param DateTimeInterface $end
 * @return int
 */
function countDaysByName($dayName, \DateTimeInterface $start, \DateTimeInterface $end)
{
    $count = 0;
    $interval = new \DateInterval('P1D');
    $period = new \DatePeriod($start, $interval, $end);

    foreach($period as $day){
        if($day->format('D') === ucfirst(substr($dayName, 0, 3))){
            $count ++;
        }
    }
    return $count;
}
like image 108
vascowhite Avatar answered Oct 02 '22 16:10

vascowhite


You could create a function that uses strtotime() recursively to count the number of days. Since strtotime("next monday"); works just fine.

function daycount($day, $startdate, $counter)
{
    if($startdate >= time())
    {
        return $counter;
    }
    else
    {
        return daycount($day, strtotime("next ".$day, $startdate), ++$counter);
    }
}

echo daycount("monday", strtotime("01.01.2009"), 0);

Hopefully this is something you're looking for :)

like image 39
Ólafur Waage Avatar answered Oct 02 '22 16:10

Ólafur Waage