我有一个PHP函数,根据当前时间是否在任意数量的预定义“hotzones”中返回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;
但是,我必须每年两次手动更新夏令时,我不得不认为这比我计算的hackish“offset”有更自然,更优雅的方法。有没有人遇到过更好的方法,这会考虑到DST?
答案 0 :(得分:2)
您可以使用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是首选方式。另请阅读Sven的评论。 (感谢)