views:

220

answers:

3

Hi,

I need to add working hours to a timestamp. Working hours are from 8am to 6pm. Lets say we have 2pm and I have to add 6 hours. Result should be 10am... any guesses?

Thanks.

A: 

Hey.

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".

Atli
It's working but only in case of real hours... not working hours, because result have to be in range 8am and 6pm.
spamec
Ahh, I see. Seems I've been self-employed for to long. The whole "working-hour" thing didn't ring a bell xD
Atli
+4  A: 

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);
Stephen Melrose
Damm good boy ;) it's really working man, thanks!
spamec
A: 

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