根据另一个时区获取一个时区的办公时间


Get Office Hours in one timezone based on another timezone

我正在尝试编写一个函数,该函数返回人们在不同时区工作时当前是否在办公室。下面的代码似乎有效,但对我来说似乎很麻烦。我想知道是否有更好的方法。

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

不需要原始时区,然后计算原始时区和远程时区之间的偏移量;这可以在没有它的情况下完成。办公室位于哪个时区并不重要,办公时间$office_hours始终适用于当地时间。说到这里,你可以删除一半的计算。

用:

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

演示