calc the working hours between 2 dates in PHP

前端 未结 3 1300
南方客
南方客 2020-12-03 23:49

I have a function to return the difference between 2 dates, however I need to work out the difference in working hours, assuming Monday to Friday (9am to 5:30pm):

3条回答
  •  一个人的身影
    2020-12-04 00:39

    This example uses PHP's built in DateTime classes to do the date math. How I approached this was to start by counting the number of full working days between the two dates and then multiply that by 8 (see notes). Then it gets the hours worked on the partial days and adds them to the total hours worked. Turning this into a function would be fairly straightforward to do.

    Notes:

    • Does not take timestamps into account. But you already know how to do that.
    • Does not handle holidays. (That can be easily added by using an array of holidays and adding it to where you filter out Saturdays and Sundays).
    • Requires PHP 5.3.6+
    • Assumes an 8 hour workday. If employees do not take lunch change $hours = $days * 8; to $hours = $days * 8.5;

    .

    modify('+1 day');
    $start->modify('midnight');
    
    // Set second datetime to midnight of that day
    $end = clone $date2;
    $end->modify('midnight');
    
    // Count the number of full days between both dates
    $days = 0;
    
    // Loop through each day between two dates
    $interval = new DateInterval('P1D');
    $period = new DatePeriod($start, $interval, $end);
    foreach ($period as $dt) {
        // If it is a weekend don't count it
        if (!in_array($dt->format('l'), array('Saturday', 'Sunday'))) {
            $days++;
        }
    }
    
    // Assume 8 hour workdays
    $hours = $days * 8;
    
    // Get the number of hours worked on the first day
    $date1->modify('5:30 PM');
    $diff = $date1->diff($start);
    $hours += $diff->h;
    
    // Get the number of hours worked the second day
    $date1->modify('8 AM');
    $diff = $date2->diff($end);
    $hours += $diff->h;
    
    echo $hours;
    

    See it in action

    Reference

    • DateTime Class
    • DatePeriod Class
    • DateInterval Class

提交回复
热议问题