检查工作时间 - 改进代码/逻辑

时间:2014-02-26 13:17:42

标签: php datetime

我有一个系统可以检查当前时间是否在香港工作。 我确定工作时间是从上午9点到下午6点。 我的代码正在运行,但我觉得有一种更好/更漂亮的方式来编写IF条件。

当香港当前时间不是工作时间时,该功能会返回True。 它也将在当天结束前15分钟(下午6点)返回TRUE(在香港的休息时间),并在开放时间前30分钟返回FALSE(在香港的工作时间)。

function hkOffHours($endHour = 18, $startHour = 9) {
    $offHour = FALSE;

    // create the DateTimeZone object for later
    $dtzone = new DateTimeZone('Asia/Hong_Kong');

    // first convert the timestamp into a string representing the local time
    $time = date('r', time());

    // now create the DateTime object for this time
    $dtime = new DateTime($time);

    // convert this to the user's timezone using the DateTimeZone object
    $dtime->setTimeZone($dtzone);

    // print the time using your preferred format
    $time = $dtime->format('g:i A m/d/y');

    $hour = $dtime->format('G');
    $min  = $dtime->format('i');
    $day  = $dtime->format('D');

    // if weekend
    if(($day == 'Sun' || $day == 'Sat') )
    {
       $offHour = TRUE;
    }

    // if out of office hours
    if (
        ($admin_group == '1') &&
        (
           ( $hour == ($endHour-1) && $min>=45 ) ||
           ( $hour >= $endHour ) ||
           ( $hour == ($startHour-1) && $min <= 30 ) ||
           ( $hour <= ($startHour -2))
        )
    ) 
    {
        $offHour = TRUE;  
    } 

    return $offHour;        
} 

我会很感激你的想法。

1 个答案:

答案 0 :(得分:0)

好吧,我首先想到的是你可以通过将它分成几个方法和一个类来重构它,如果你还没有这样做的话。

例如:

    $offHour = FALSE;

    // create the DateTimeZone object for later
    $dtzone = new DateTimeZone('Asia/Hong_Kong');

    // first convert the timestamp into a string representing the local time
    $time = date('r', time());

    // now create the DateTime object for this time
    $dtime = new DateTime($time);

    // convert this to the user's timezone using the DateTimeZone object
    $dtime->setTimeZone($dtzone);

    // print the time using your preferred format
    $time = $dtime->format('g:i A m/d/y');

    $hour = $dtime->format('G');
    $min  = $dtime->format('i');
    $day  = $dtime->format('D');

以上所有字段都可以是类变量。

if(($day == 'Sun' || $day == 'Sat') )

这可以移动到单独的函数,称为isWeekend()

if (
    ($admin_group == '1') &&
    (
       ( $hour == ($endHour-1) && $min>=45 ) ||
       ( $hour >= $endHour ) ||
       ( $hour == ($startHour-1) && $min <= 30 ) ||
       ( $hour <= ($startHour -2))
    )
) 
{
    $offHour = TRUE;  
}

可以将其移至isOutOfOfficeHours()

全班模板:

class workingHours{

  private $dtzone;
  private ...
  (...)

  public function __construct($dtzone....){
    //setup values of class members
  }

  private function isWeekend(){} //see above

  private function isOutOfOfficeHours(){} //also see above

  public function hkOffHours(){
    return $this->isWeekend() || $this->isOutOfOfficeHours();
  }
}

当然注意到我写得很快,我在工作。因此,我的代码逻辑可能与您的代码逻辑不完全兼容。无论如何,我希望你能得到这个想法。

还有一个最后的想法 - 有很多关于重构的书。试试吧!他们会让你成为一个更好的程序员。

相关问题