【问题标题】:Add working hours to timestamp将工作时间添加到时间戳
【发布时间】:2011-01-10 08:14:18
【问题描述】:

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

谢谢。

【问题讨论】:

  • 我认为我们需要更多细节。根据您的示例,您是仅处理离散时间,还是正如您的问题所暗示的那样,它实际上使用时间戳?我还怀疑,在该算法的任何实际应用中,您都需要考虑边界条件,例如下午 6 点真的是一个有效的回应吗?
  • 你是对的......我有开始日期作为时间戳。然后我必须增加小时数(如 3 等)。你关于边界的问题是正确的(关于那个案例没有问题),下午 6 点无效,所以结果应该是上午 8 点(具体的日期时间而不是小时)。

标签: php calendar date business-logic


【解决方案1】:

如果是真正的时间戳,只需加上相当于 6 小时的秒数即可。

$timestamp += 3600 * 6;

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

【讨论】:

  • 它可以工作,但仅适用于实际工作时间......不是工作时间,因为结果必须在上午 8 点和下午 6 点之间。
  • 啊,我明白了。看来我做个体户很久了。整个“工作时间”的事情并没有响起 xD
【解决方案2】:

试试这个坏男孩。

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

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

【讨论】:

  • 如何添加休息日和节假日?圣诞节、7 月 4 日、劳动节等?
【解决方案3】:

更紧凑的版本:

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

【讨论】:

    猜你喜欢
    • 2023-03-31
    • 2015-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-26
    • 2014-03-18
    • 2021-12-03
    • 2010-11-10
    相关资源
    最近更新 更多