计算2个日期之间的小时数 - 不包括周末

时间:2012-07-26 11:25:59

标签: php datetime date

使用此代码:Calculate number of hours between 2 dates in PHP我想计算两个时间戳之间的小时数。

我现在需要的是能够从这个计数中排除周末时间吗?

e.g。对于以下2个时间戳,我希望小时数为24而不是72。

$datetime1 = "2012-07-20 12:00:00";
$datetime2 = "2012-07-23 12:00:00";

1 个答案:

答案 0 :(得分:6)

以下代码应该有效。我假设$ datetime1总是小于$ datetime2。

$datetime1 = "2012-07-20 12:00:00"; 
$datetime2 = "2012-07-23 12:00:00";

$timestamp1 = strtotime($datetime1);
$timestamp2 = strtotime($datetime2);

$weekend = array(0, 6);

if(in_array(date("w", $timestamp1), $weekend) || in_array(date("w", $timestamp2), $weekend))
{
    //one of the dates is weekend, return 0?
    return 0;
}

$diff = $timestamp2 - $timestamp1;
$one_day = 60 * 60 * 24; //number of seconds in the day

if($diff < $one_day)
{
    return floor($diff / 3600);
}

$days_between = floor($diff / $one_day);
$remove_days  = 0;

for($i = 1; $i <= $days_between; $i++)
{
   $next_day = $timestamp1 + ($i * $one_day);
   if(in_array(date("w", $next_day), $weekend))
   {
      $remove_days++; 
   }
}

return floor(($diff - ($remove_days * $one_day)) / 3600);