将工作时间添加到时间戳

问题描述:

我需要将工作时间添加到时间戳。工作时间为上午8点至下午6点。假设我们有2点,我必须增加6个小时。结果应该是上午10点...任何猜测?将工作时间添加到时间戳

谢谢。

+0

我认为我们需要一些详细信息。根据您的示例,您是否只处理离散小时,或者它是否实际上使用时间戳,正如您的问题所暗示的那样?我也怀疑在这个算法的任何实际应用中,你都需要考虑边界条件,例如下午6点实际上是一个有效的回应? – 2010-01-28 09:53:11

+0

你是对的...我有开始日期作为时间戳。然后,我不得不增加几个小时(像3等)。你关于边界的问题是正确的(关于这种情况并没有),而下午6点是无效的,所以结果应该是早上8点(具体的日期时间不只是一小时)。 – spamec 2010-01-28 10:04:03

试试这个坏男孩。

您可以指定是否将周末包括为工作日等。不考虑假期。

<?php 

function addWorkingHours($timestamp, $hoursToAdd, $skipWeekends = false) 
{ 
    // Set constants 
    $dayStart = 8; 
    $dayEnd = 16; 

    // For every hour to add 
    for($i = 0; $i < $hoursToAdd; $i++) 
    { 
     // Add the hour 
     $timestamp += 3600; 

     // If the time is between 1800 and 0800 
     if ((date('G', $timestamp) >= $dayEnd && date('i', $timestamp) >= 0 && date('s', $timestamp) > 0) || (date('G', $timestamp) < $dayStart)) 
     { 
      // If on an evening 
      if (date('G', $timestamp) >= $dayEnd) 
      { 
       // Skip to following morning at 08XX 
       $timestamp += 3600 * ((24 - date('G', $timestamp)) + $dayStart); 
      } 
      // If on a morning 
      else 
      { 
       // Skip forward to 08XX 
       $timestamp += 3600 * ($dayStart - date('G', $timestamp)); 
      } 
     } 

     // If the time is on a weekend 
     if ($skipWeekends && (date('N', $timestamp) == 6 || date('N', $timestamp) == 7)) 
     { 
      // Skip to Monday 
      $timestamp += 3600 * (24 * (8 - date('N', $timestamp))); 
     } 
    } 

    // Return 
    return $timestamp; 
} 

// Usage 
$timestamp = time(); 
$timestamp = addWorkingHours($timestamp, 6); 
+0

达姆好孩子;)这真的是工作的人,谢谢! – spamec 2010-01-28 10:33:52

如果它是一个真正的时间戳,你只需要添加相当于6小时的秒。

$timestamp += 3600 * 6; 

如果不是我们需要知道“时间戳”的真实格式。

+0

它的工作,但只有在实际情况下......不工作时间,因为结果必须在上午8点和下午6点范围内。 – spamec 2010-01-28 09:46:30

+3

啊,我明白了。似乎我一直是自雇人士。整个“工作时间”的事情没有响钟xD – Atli 2010-01-28 10:45:29

一个更紧凑的版本:

function addWhours($timestamp, $hours, $skipwe=false, $startDay='8', $endDay='18') 
{ 
    $notWorkingInterval = 3600 * (24 - ($endDay - $startDay)); 
    $timestamp += 3600*$hours; 

    $our = date('H', $timestamp); 
    while ($our < $startDay && $our >= $endDay) { 
    $timestamp += $notWorkingInterval; 
    $our = date('H', $timestamp); 
    } 

    $day = date('N', $timestamp); 
    if ($skipwe && $day >5) { 
    $timestamp += (8-$day)*3600*24; 
    } 

    return $timestamp; 
}