在PHP中计算两个日期之间的工作小时数

4

我有一个函数可以返回两个日期之间的差异,但是我需要计算工作时间的差异,假设周一到周五(上午9点到下午5:30)为工作时间:

//DATE DIFF FUNCTION
// Set timezone
date_default_timezone_set("GMT");

// Time format is UNIX timestamp or
// PHP strtotime compatible strings
function dateDiff($time1, $time2, $precision = 6) {
    // If not numeric then convert texts to unix timestamps
    if (!is_int($time1)) {
        $time1 = strtotime($time1);
    }
    if (!is_int($time2)) {
        $time2 = strtotime($time2);
    }

    // If time1 is bigger than time2
    // Then swap time1 and time2
    if ($time1 > $time2) {
        $ttime = $time1;
        $time1 = $time2;
        $time2 = $ttime;
    }

    // Set up intervals and diffs arrays
    $intervals = array('year','month','day','hour','minute','second');
    $diffs = array();

    // Loop thru all intervals
    foreach ($intervals as $interval) {
        // Set default diff to 0
        $diffs[$interval] = 0;
        // Create temp time from time1 and interval
        $ttime = strtotime("+1 " . $interval, $time1);
        // Loop until temp time is smaller than time2
        while ($time2 >= $ttime) {
            $time1 = $ttime;
            $diffs[$interval]++;
            // Create new temp time from time1 and interval
            $ttime = strtotime("+1 " . $interval, $time1);
        }
    }

    $count = 0;
    $times = array();
    // Loop thru all diffs
    foreach ($diffs as $interval => $value) {
        // Break if we have needed precission
        if ($count >= $precision) {
            break;
        }
        // Add value and interval 
        // if value is bigger than 0
        if ($value > 0) {
            // Add s if value is not 1
            if ($value != 1) {
                $interval .= "s";
            }
            // Add value and interval to times array
            $times[] = $value . " " . $interval;
            $count++;
        }
    }

    // Return string with times
    return implode(", ", $times);
}

日期1 = 2012年3月24日03:58:58
日期2 = 2012年3月22日11:29:16

有没有简单的方法来计算一周内的工作小时百分比并使用上述函数来计算差值 - 我已经尝试了这个想法,得到了一些非常奇怪的数字...

或者有更好的方法吗?


你不能做一周的百分比这样的事情:如果你有一个完整的星期六和星期天,那就是工作周的0%,大约是一周的29%。最快的方法是计算出全天的工作时间,然后计算出在这些全天工作之前和之后的部分天数。 - Jerome
3个回答

4
这个例子使用PHP内置的DateTime类来进行日期计算。我的方法是先计算两个日期之间的完整工作日数量,然后将其乘以8(见注释)。然后获取部分工作日的工作小时数,并将其添加到总工作小时数中。将其转换为函数将是相当简单的。
注: - 不考虑时间戳。但你已经知道如何处理它。 - 不处理假期。(可以通过使用假期数组并将其添加到过滤掉周六和周日的位置来轻松添加。) - 需要PHP 5.3.6+。 - 假设一天工作8小时。如果员工不吃午饭,请将 `$hours = $days * 8;` 更改为 `$hours = $days * 8.5;`。
<?php
// Initial datetimes
$date1 = new DateTime('2012-03-22 11:29:16');
$date2 = new DateTime('2012-03-24 03:58:58');

// Set first datetime to midnight of next day
$start = clone $date1;
$start->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;

点击此处查看

参考资料


需要什么功能才能使用5.3.6版本? - Theodore R. Smith
PHPgolf的PHP版本:5.3.3-phpGolf http://www.phpgolf.org/doc 这是从2010年7月开始的!已经过时了3年半了 ;o - Theodore R. Smith
@TheodoreR.Smith DateTime 功能。如果您在 PHP 5.3 的早期版本中运行此功能,将会得到不正确的结果。点击“查看演示”链接,以了解我的意思。 - John Conde
我尝试将固定假期添加到上述解决方案中。我尝试了以下代码: if($date > $startofday && $date <= $endofday && !in_array($date->format('n'), array(5,6,7))){ $count++; } 但它只给出了天数。我尝试使用'j'代替,但无法找到正确的格式。我尝试了以下代码: if($date > $startofday && $date <= $endofday && !in_array($date->format('j'), array(5,6,7,9))){ $count++; } 意思是第5、6、7、9天。有什么建议吗? - Kissa Mia

2
这是我的解决方案。
我的解决方案检查原始日期的开始和结束时间,并根据工作日的实际开始和结束时间进行调整(如果原始开始时间早于工作日的开放时间,则将其设置为后者)。
在对开始和结束时间都进行此操作之后,比较这些时间以检索 DateInterval 差异,计算总天数、小时等。然后检查日期范围是否包含任何周末日,如果发现,则从差异中减少一天的总数。
最后,按照注释计算小时。 :)
感谢John为这个解决方案提供了灵感,特别是使用DatePeriod来检查周末。
如果有人找到漏洞,我会很高兴更新。
// Settings
$workStartHour = 9;
$workStartMin = 0;
$workEndHour = 17;
$workEndMin = 30;
$workdayHours = 8.5;
$weekends = ['Saturday', 'Sunday'];
$hours = 0;

// Original start and end times, and their clones that we'll modify.
$originalStart = new DateTime('2012-03-22 11:29:16');
$start = clone $originalStart;

// Starting on a weekend? Skip to a weekday.
while (in_array($start->format('l'), $weekends))
{
    $start->modify('midnight tomorrow');
}

$originalEnd = new DateTime('2012-03-24 03:58:58');
$end = clone $originalEnd;

// Ending on a weekend? Go back to a weekday.
while (in_array($end->format('l'), $weekends))
{
    $end->modify('-1 day')->setTime(23, 59);
}

// Is the start date after the end date? Might happen if start and end
// are on the same weekend (whoops).
if ($start > $end) throw new Exception('Start date is AFTER end date!');

// Are the times outside of normal work hours? If so, adjust.
$startAdj = clone $start;

if ($start < $startAdj->setTime($workStartHour, $workStartMin))
{
    // Start is earlier; adjust to real start time.
    $start = $startAdj;
}
else if ($start > $startAdj->setTime($workEndHour, $workEndMin))
{
    // Start is after close of that day, move to tomorrow.
    $start = $startAdj->setTime($workStartHour, $workStartMin)->modify('+1 day');
}

$endAdj = clone $end;

if ($end > $endAdj->setTime($workEndHour, $workEndMin))
{
    // End is after; adjust to real end time.
    $end = $endAdj;
}
else if ($end < $endAdj->setTime($workStartHour, $workStartMin))
{
    // End is before start of that day, move to day before.
    $end = $endAdj->setTime($workEndHour, $workEndMin)->modify('-1 day');
}

// Calculate the difference between our modified days.
$diff = $start->diff($end);

// Go through each day using the original values, so we can check for weekends.
$period = new DatePeriod($start, new DateInterval('P1D'), $end);

foreach ($period as $day)
{
    // If it's a weekend day, take it out of our total days in the diff.
    if (in_array($day->format('l'), ['Saturday', 'Sunday'])) $diff->d--;
}

// Calculate! Days * Hours in a day + hours + minutes converted to hours.
$hours = ($diff->d * $workdayHours) + $diff->h + round($diff->i / 60, 2);

这两个答案都是错误的,请问有人能正确回答这个问题吗? - user794846
不要有那种态度。 - Aken Roberts
@Cryode 这是我找到的唯一一个代码,从我所知道的情况来看,它可以100%地工作。所有其他答案,无论是在这个问题上还是其他问题上,都在某些日期范围内出现了错误(例如“2017-01-24 00:00:00” - “2017-01-30 09:45:00”在任何其他答案中都不起作用!)。谢谢! - superphonic
忘了吧,我刚把它搞坏了。2017-02-08 19:00:00 - 2017-02-08 22:00:00 的结果是16小时。 - superphonic
@superphonic 我忘记了这个答案。你找到另一个问题,太棒了!如果您找到解决方案,请告诉我。 :) - Aken Roberts

1
正如古语所说:“欲速则不达”,虽然这并不是最佳方式,但至少能为我返回正确的工时数。
function biss_hours($start, $end){

    $startDate = new DateTime($start);
    $endDate = new DateTime($end);
    $periodInterval = new DateInterval( "PT1H" );

    $period = new DatePeriod( $startDate, $periodInterval, $endDate );
    $count = 0;

      foreach($period as $date){

           $startofday = clone $date;
           $startofday->setTime(8,30);

           $endofday = clone $date;
           $endofday->setTime(17,30);

    if($date > $startofday && $date <= $endofday && !in_array($date->format('l'), array('Sunday','Saturday'))){

        $count++;
    }

}

//Get seconds of Start time
$start_d = date("Y-m-d H:00:00", strtotime($start));
$start_d_seconds = strtotime($start_d);
$start_t_seconds = strtotime($start);
$start_seconds = $start_t_seconds - $start_d_seconds;

//Get seconds of End time
$end_d = date("Y-m-d H:00:00", strtotime($end));
$end_d_seconds = strtotime($end_d);
$end_t_seconds = strtotime($end);
$end_seconds = $end_t_seconds - $end_d_seconds;

$diff = $end_seconds-$start_seconds;

if($diff!=0):
    $count--;
endif;

$total_min_sec = date('i:s',$diff);

return $count .":".$total_min_sec;
}

$start = '2014-06-23 12:30:00';
$end = '2014-06-27 15:45:00';

$go = biss_hours($start,$end);
echo $go;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接