开发者

Add working hours to timestamp

I need to add working hours to a timestamp. Working hours are from 8am to 6pm. Lets say we h开发者_如何学Pythonave 2pm and I have to add 6 hours. Result should be 10am... any guesses?

Thanks.


Try this bad boy.

You can specify whether to include weekends as working days, etc. Doesn't take into account holidays.

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


A more compact version:

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


If it is a real timestamp, you just need to add the seconds equivelent to 6 hours.

$timestamp += 3600 * 6;

If not we need to know the real format of your "timestamp".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜