Given two dates what is the best way of finding the number of weekdays in PHP?

前端 未结 4 1668
自闭症患者
自闭症患者 2021-01-24 08:53

The title is pretty much self explanatory. Given two dates what is the best way of finding the number of week days using PHP? Week days being Monday to Friday.

For insta

相关标签:
4条回答
  • 2021-01-24 09:49
            $datefrom = strtotime($datefrom, 0);
            $dateto = strtotime($dateto, 0);
    
            $difference = $dateto - $datefrom;
    
            $days_difference = floor($difference / 86400);
            $weeks_difference = floor($days_difference / 7); // Complete weeks
    
            $first_day = date("w", $datefrom);
            $days_remainder = floor($days_difference % 7);
    
            $odd_days = $first_day + $days_remainder; // Do we have a Saturday or Sunday in the remainder?
            if ($odd_days > 7) { // Sunday
                $days_remainder--;
            }
            if ($odd_days > 6) { // Saturday
                $days_remainder--;
            }
    
            $datediff = ($weeks_difference * 5) + $days_remainder;
    

    From here: http://www.addedbytes.com/php/php-datediff-function/

    0 讨论(0)
  • 2021-01-24 09:51

    The best way is to iterate through all dates in between the given date range, and get the day of week for each date. If it's a week day, increment a certain counter. At the end of the process you get the number of weekdays.

    The PHP functions mktime() and date() (for working with UNIX timestamps) are your friends here.

    0 讨论(0)
  • 2021-01-24 09:54

    If you are creating an invoicing system, you have to think about the bank holidays, Easter, etc. It is not simple to compute it.

    The best solution I have ever seen is to pregenerate a table with days and its type to SQL database (row per day = 365 rows per year) and then perform simple count query with proper selection (WHERE clause).

    You can find this solution fully described in Joe Celko's Thinking in Sets: Auxiliary, Temporal, and Virtual Tables in SQL

    0 讨论(0)
  • 2021-01-24 09:57

    One way would be to convert the dates to unix timestamps using strtotime(...), subtracting the results and div'ing with 86400 (24*60*60):

    $dif_in_seconds = abs(strtotime($a) - strtotime($b));
    $daysbetween = $dif_in_seconds / 86400;
    

    ETA: Oh.. You meant weekdays as in Mon-Fri.. Didn't see that at first..

    0 讨论(0)
提交回复
热议问题