douming4359 2016-07-26 09:11
浏览 34
已采纳

从开始和结束日期分割的工作日和周末时间不适用于不同的周

Need to find total hours splitting the hours for the weekend which is Friday, Saturday and Sunday and other weekdays. Using the following piece of code but it's not yielding the desired result.

$start_day = date('w', $start_time);
        $start_hour = date('G', $start_time);
        $end_day = date('w', $end_time);
        $end_hour = date('G', $end_time);
        $normal_hours = $surge_hours = 0;


        for (;($start_hour < 24 && $start_day <= $end_day); $start_hour++) {

            switch ($start_day) {
                case 0: $surge_hours++;
                    break;
                case 5: $surge_hours++;
                    break;
                case 6: $surge_hours++;
                    break;
                case 1: $normal_hours++;
                    break;
                case 2: $normal_hours++;
                    break;
                case 3: $normal_hours++;
                    break;
                case 4: $normal_hours++;
                    break;
            }
            echo __line__;
            echo "<pre>";
            print_r('surgehours'.$surge_hours);
            echo "<br/>";
            print_r('normalhours'.$normal_hours);
            echo "<pre/>";
            if ($start_hour == 23) {
                $start_hour = 0;
                $start_day++;
            }

            if ($start_day == $end_day) {
                if ($start_hour == $end_hour)
                    break;
            }
        }

Failing Uses cases:

If the start day is Friday, i.e.: 29 July and end day is 1 August ( $start_day = 5 and $end_day = 1 )
It does not go into the loop.

Any ideas how to calculate the hours?

  • 写回答

2条回答 默认 最新

  • douzhouqin6223 2016-07-26 10:02
    关注

    The new code is below (cleaned it up and changed the comparison operator to < instead of <= which prevented that last extra hour from coming through):

        <?php
    $start_time = strtotime('next friday 11am');
    $end_time = $start_time + (60*60*24*3);
    
    function allocate_hour($timestamp) {
        if(date('w',$timestamp) >= 5 OR date('w',$timestamp) == 0) {
            return 0;
        } else { return 1; }
    }
    
    $weekdayhours = 0;
    $weekendhours = 0;
    for($thistime=$start_time;$thistime<$end_time;$thistime+=3600){
        if(allocate_hour($thistime) === 1) { $weekdayhours++; } else { $weekendhours++; } // add 1 for each hour.
    }
    
    echo 'Weekday hours: '.$weekdayhours;
    echo '<BR>weekend hours: '.$weekendhours;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?