Clarkey
Clarkey

Reputation: 708

PHP - Exclude all non-business hours / days from time difference

I have a table which shows the time since a job was raised.

// These are unix epoch times...
$raised = 1360947684;
$now = 1361192598;
$difference = 244914;

$difference needs to exclude any time outside of business hours (ex, 9-5 and weekends).

How could I tackle this?

Upvotes: 3

Views: 1717

Answers (3)

LPOPYui
LPOPYui

Reputation: 1242

Very bad idea, but I had no choice because I'm on php 5.2

<?php
date_default_timezone_set('Asia/Seoul');

$start = 1611564957;
$end = 1611670000;
$res = 0;
for($i = $start; $i<$end; $i++){

    $h = date("H", $i);
    if($h >= 9 && $h < 18){
        //echo date("Y-m-d H:i:s", $i) . "<br>";
        $res = $res + 1;
    }
}
echo $res;

Upvotes: 0

Max
Max

Reputation: 180

The thing you have to do are 3 in numbers.

  1. You take your start date and calculate the rest time on this day (if it is a business day)
  2. You take your end date and calulate the time on this day and
  3. you take the days in between and multiply them with your business hours (just those, that are business days)

And with that you are done.

Find a little class attached, which does those things. Be aware that there is no error handling, time zone settings, daylight saving time, ...

input:

  • start date
  • end date

output:

  • difference time in seconds

adjustable constants:

  • Business hours
  • Days that are not business days

Upvotes: 5

Amelia
Amelia

Reputation: 2970

Use DateTime.

Using UNIX time for this is slightly absurd, and you would have to literally remake DateTime.
Look up relative formats where you can specify the hour on the day, e.g.

$date = new DateTime($raised);
$business_start = new DateTime("09:00"); // 9am today
$business_end = new DateTime("17:00"); // 5pm today

The rest is for you to work out.

Oh, and instead of start/end, you could probably use DateInterval with a value of P8H ("period 8 hours")

The problem with using timestamps directly is that you are assigning a context to a counter of seconds. You have to work backwards from the times you want to exclude and work out their timestamps beforehand. You might want to try redesigning your storage of when a job is raised. Maybe set an expiry time for it instead?

Upvotes: -1

Related Questions