1

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

谢谢。

4

3 回答 3

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);
于 2010-01-28T10:27:19.473 回答
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;
}
于 2010-01-28T11:10:35.143 回答
-2

如果它是一个真正的时间戳,您只需将秒数添加到 6 小时。

$timestamp += 3600 * 6;

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

于 2010-01-28T09:41:20.823 回答