优雅的一周中的时间功能


elegant time-of-week function

我有一个PHP函数,它根据时间当前是否在任何数量的预定义"热区"中返回bool。时区是美国/芝加哥(UTC-0600)。以下工作:

$d = 60*60;                    /* duration of hotzone */
$o = -(3*24+18)*3600;          /* offset to bring UNIX epoch to 12a Sun local*/
$curTime = (time()-$o)%604800; /* time since 12a Sun */
/* Hotzones */
$hotTime = array();
$hotTime[0 ] = (0*24+11)*3600; /* 11a Sun */
$hotTime[1 ] = (0*24+18)*3600; /*  6p Sun */
$hotTime[2 ] = (2*24+19)*3600; /*  7p Tue */
$hotTime[3 ] = (3*24+ 6)*3600; /*  6a Wed */
$hotTime[4 ] = (3*24+11)*3600; /* 11a Wed */
$hotTimes = count($hotTime);
for ($i = $hotTimes-1; $i>=0; $i--) {
  if (($curTime > $hotTime[$i])&&($curTime < $hotTime[$i]+$d)) {
    return true;
  }
}
return false;

然而,我每年必须手动更新两次夏令时,我必须认为有一种比我计算的"偏移"更自然、更优雅的方法来做到这一点。有没有人能想出一种更好的方法来做到这一点,考虑到夏令时?

您可以使用DateTime类进行以下操作:

$hottimes = array (
    array(
        'start'=> new DateTime('Sun 11:00:00 America/Chicago'),
        'stop'=> new DateTime('Sun 12:00:00 America/Chicago')
    ),
    array(
        'start'=> new DateTime('Sun 18:00:00 America/Chicago'),
        'stop'=> new DateTime('Sun 19:00:00 America/Chicago')
    ),
    array(
        'start'=> new DateTime('Tue 19:00:00 America/Chicago'),
        'stop'=> new DateTime('Tue 20:00:00 America/Chicago')
    ),
    array(
        'start'=> new DateTime('Wed 06:00:00 America/Chicago'),
        'stop'=> new DateTime('Wed 07:00:00 America/Chicago')
    ),
    array(
        'start'=> new DateTime('Wed 11:00:00 America/Chicago'),
        'stop'=> new DateTime('Wed 12:00:00 America/Chicago')
    )
);
$now = new DateTime();
foreach($hottimes as $hotime) {
    if($now >= $hotime['start'] && $now < $hotime['stop']) {
        return true;
    }
}

对于这样的事情,您不应该使用UNIX时间戳。使用DateTime是最好的方法。另请阅读斯文的评论。(谢谢)