将工作时间添加到时间戳

时间:2010-01-28 09:38:37

标签: php calendar date business-logic

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

感谢。

3 个答案:

答案 0 :(得分:8)

试试这个坏孩子。

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

<?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);

答案 1 :(得分:0)

更紧凑的版本:

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;
}

答案 2 :(得分:-2)

如果是真正的时间戳,您只需要添加相当于6小时的秒数。

$timestamp += 3600 * 6;

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