Calculate business days

后端 未结 30 1857
猫巷女王i
猫巷女王i 2020-11-22 05:16

I need a method for adding \"business days\" in PHP. For example, Friday 12/5 + 3 business days = Wednesday 12/10.

At a minimum I need the code to understand weekend

30条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 06:15

    My version based on the work by @mcgrailm... tweaked because the report needed to be reviewed within 3 business days, and if submitted on a weekend, the counting would start on the following Monday:

    function business_days_add($start_date, $business_days, $holidays = array()) {
        $current_date = strtotime($start_date);
        $business_days = intval($business_days); // Decrement does not work on strings
        while ($business_days > 0) {
            if (date('N', $current_date) < 6 && !in_array(date('Y-m-d', $current_date), $holidays)) {
                $business_days--;
            }
            if ($business_days > 0) {
                $current_date = strtotime('+1 day', $current_date);
            }
        }
        return $current_date;
    }
    

    And working out the difference of two dates in terms of business days:

    function business_days_diff($start_date, $end_date, $holidays = array()) {
        $business_days = 0;
        $current_date = strtotime($start_date);
        $end_date = strtotime($end_date);
        while ($current_date <= $end_date) {
            if (date('N', $current_date) < 6 && !in_array(date('Y-m-d', $current_date), $holidays)) {
                $business_days++;
            }
            if ($current_date <= $end_date) {
                $current_date = strtotime('+1 day', $current_date);
            }
        }
        return $business_days;
    }
    

    As a note, everyone who is using 86400, or 24*60*60, please don't... your forgetting time changes from winter/summer time, where a day it not exactly 24 hours. While it's a little slower the strtotime('+1 day', $timestamp), it much more reliable.

提交回复
热议问题