【问题标题】:Get Office Hours in one timezone based on another timezone根据另一个时区获取一个时区的办公时间
【发布时间】:2013-11-14 04:33:35
【问题描述】:

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

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

    ?>

【问题讨论】:

    标签: php timezone timezone-offset


    【解决方案1】:

    不需要原始时区,然后计算原始时区和远程时区之间的偏移量;这可以在没有它的情况下完成。 无论办公室在哪个时区,办公时间$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;
    }
    

    Demo

    【讨论】:

    • 哦,当然……这要容易得多!好东西,谢谢:)
    • @RidIculous:np mate,我很高兴能帮上忙。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-22
    • 2014-12-21
    • 1970-01-01
    相关资源
    最近更新 更多