Question

I'm trying to code a function that returns whether people are currently in their office when they work in a different timezone. Below code seems to work, but seems cumbersome to me. I wonder if there is a better approach.

    <?
    function isInoffice($remote_tz){

        $office_hours = array(
            'Monday'    =>'9:00-17:00',
            'Tuesday'   =>'9:00-17:00',
            'Wednesday' =>'9:00-17:00',
            'Thursday'  =>'9:00-17:00',
            'Friday'    =>'9:00-17:00',
            'Saturday'  =>'9:00-12:00',
            'Sunday'    =>'0:00-0:00'
            );

        $origin_tz      = 'Australia/Melbourne';
        $origin_dtz             = new DateTimeZone($origin_tz);
        $remote_dtz             = new DateTimeZone($remote_tz);
        $origin_dt      = new DateTime("now", $origin_dtz);
        $remote_dt      = new DateTime("now", $remote_dtz);
        $offset             = $origin_dtz->getOffset($origin_dt) - $remote_dtz->getOffset($remote_dt);

        $date   = getdate();
        $local  = $office_hours[$date['weekday']];

        $x      = explode('-',$local);
        $start  = str_replace(':','',$x[0]);
        $end     = str_replace(':','',$x[1]);

        $now = date('Hm',time()-$offset);

    //echo "$start - $end - $now";

        if( ($now>$start) && ($now < $end)){
            return 1;   
        } else {
            return 0;       
        }

    }

    echo isInoffice('America/New_York');

    ?>
Was it helpful?

Solution

You do not need original timezone, and then calculate offset between original and remote timezone; this can be accomplished without that. It doesn't matter in which timezone office is, office hours $office_hours are always applied for local time. Said that, you can delete half of your calculation.

Use:

var_dump( isOfficeTime('America/New_York') ); # bool(false)
var_dump( isOfficeTime('Europe/Berlin') );    # bool(true)
var_dump( isOfficeTime('Australia/Sydney') ); # bool(false)
var_dump( isOfficeTime('Asia/Hong_Kong') );   # bool(false)

Function:

function isOfficeTime($tz) {
    $office_hours = array(
        'Monday'    => array('9:00', '17:00'),
        'Tuesday'   => array('9:00', '17:00'),
        'Wednesday' => array('9:00', '17:00'),
        'Thursday'  => array('9:00', '17:00'),
        'Friday'    => array('9:00', '17:00'),
        'Saturday'  => array('9:00', '12:00'),
        'Sunday'    => array('0:00', '0:00'),
    );

    $tz  = new DateTimeZone($tz);
    $now = new DateTime('now', $tz);
    $start = new DateTime($office_hours[$now->format('l')][0], $tz);
    $end   = new DateTime($office_hours[$now->format('l')][1], $tz);

    return $start != $end && $start <= $now && $now < $end;
}

Demo.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top