3

Using this code: Calculate number of hours between 2 dates in PHP I want to calculate the number of hours between 2 timestamps.

What I need now is to be able to exclude weekend hours from this count?

e.g. For the following 2 time stamps, I'd expect the number of Hours to be 24 instead of 72.

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

1 Answers1

6

The code below should work. I'm assuming $datetime1 is always less than $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);
Kasia Gogolek
  • 3,374
  • 4
  • 33
  • 50