3

使用此代码:计算 PHP 中 2 个日期之间的小时数我想计算 2 个时间戳之间的小时数。

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

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

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

1 回答 1

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);
于 2012-07-26T11:36:49.617 回答