Search code examples
phpdatedatetime

find cout of specific day between two date php without using any loop?


I need to find out count of a specific Day between two date. I can do this by using loop between two date, but if there is difference of 10 years(suppose) between date loop will run 10*365 times. Is any easier way to do this?
Thanks in advance


Solution

  • function countDays($day, $start, $end) {

    $start = strtotime($start);
    $end = strtotime($end);
    $datediff = $end - $start;
    
    $days =  floor($datediff / (60 * 60 * 24));
    
    
    //get the day of the week for start and end dates (0-6)
    $w = array( date('w', $start ), date('w', $end) );
    
    //get partial week day count
    if ($w[0] < $w[1])
    {            
        $partialWeekCount = ($day >= $w[0] && $day <= $w[1]);
    }else if ($w[0] == $w[1])
    {
        $partialWeekCount = $w[0] == $day;
    }else
    {
        $partialWeekCount = ($day >= $w[0] 
        $day <= $w[1]); 
    } 
    //first count the number of complete weeks, then add 1 if $day falls in a partial week. 
    return intval($days / 7) + $partialWeekCount; 
    

    }

    Function Call - countDays( 5, "2017-04-14", "2017-04-21")