Get number of weekdays in a given month

后端 未结 12 2160
无人及你
无人及你 2020-12-03 15:56

I want to calculate the number of weekdays days in a give month and year. Weekdays means monday to friday. How do i do it ?

12条回答
  •  离开以前
    2020-12-03 16:34

    I've come up with a non-loop function. Much better in terms of performance. It might seem messy but it just needs to ask PHP the first day's weekday and the month's number days: the rest are arithmetical operations based on logic.

    function countWorkDays($year, $month)
    {
        $workingWeekdays   = 5;
        $firstDayTimestamp = mktime(0, 0, 0, $month, 1, $year);
        $firstDayWeekDay   = (int)date("N", $firstDayTimestamp); //1: monday, 7: saturday
        $upToDay           = (int)date("t", $firstDayTimestamp);
    
        $firstMonday = 1 === $firstDayWeekDay ? 1 : 9 - $firstDayWeekDay;
        $wholeWeeks  = $firstMonday < $upToDay ? (int)floor(($upToDay - $firstMonday + 1) / 7) : 0;
        $extraDays   = ($upToDay - $firstMonday + 1) % 7;
    
        $initialWorkdays      = $firstMonday > 1 && $firstDayWeekDay <= $workingWeekdays ? $workingWeekdays - $firstDayWeekDay + 1 : 0;
        $workdaysInWholeWeeks = $wholeWeeks * $workingWeekdays;
        $extraWorkdays        = $extraDays <= $workingWeekdays ? $extraDays : $workingWeekdays;
    
        return $initialWorkdays + $workdaysInWholeWeeks + $extraWorkdays;
    }
    

提交回复
热议问题