Get number of weekdays in a given month

后端 未结 12 2163
无人及你
无人及你 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:33

    These functions work Without Loops.

    The functions calculate the number of weekdays using:

    • day-number of first monday in month
    • number of days in month
    // main functions 
    // weekdays in month of year
    function calculateNumberOfWeekDaysAtDate($month, $year)
    {
        // I'm sorry, I don't know the right format for the $month and $year, I hope this is right.
        // PLEASE CORRECT IF WRONG
        $firstMondayInCurrentMonth = (int) date("j", strtotime("first monday of 01-$month-$year")); //get first monday in month for calculations
        $numberOfDaysOfCurrentMonth = (int) date("t", strtotime("01-$month-$year")); // number of days in month
    
        return calculateNumberOfWeekDaysFromFirstMondayAndNumberOfMonthDays($firstMondayInCurrentMonth, $numberOfDaysOfCurrentMonth);
    }
    
    // week days in current month
    function calculateNumberOfWeekDaysInCurrentMonth()
    {
        $firstMondayInCurrentMonth = (int) date("j", strtotime("first monday of this month")); //get first monday in month for calculations
        $numberOfDaysOfCurrentMonth = (int) date("t"); // number of days in this month
    
        return calculateNumberOfWeekDaysFromFirstMondayAndNumberOfMonthDays($firstMondayInCurrentMonth, $numberOfDaysOfCurrentMonth);
    }
    
    // helper functions
    function calculateNumberOfWeekDaysFromFirstMondayAndNumberOfMonthDays($firstMondayInCurrentMonth, $numberOfDaysOfCurrentMonth)
    {
        return $numberOfWeekDays = (($start = ($firstMondayInCurrentMonth - 3)) < 0 ? 0 : $start) + floor(($numberOfDaysOfCurrentMonth - ($firstMondayInCurrentMonth - 1)) / 7) * 5 + (($rest = (($numberOfDaysOfCurrentMonth - ($firstMondayInCurrentMonth - 1)) % 7)) <= 5 ? $rest : 5);
    }
    

提交回复
热议问题