php – 优雅的星期功能
发布时间:2020-12-13 16:20:38 所属栏目:PHP教程 来源:网络整理
导读:我有一个 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
我有一个
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; 但是,我必须每年两次手动更新夏令时,我不得不认为这比我计算的黑客“偏移”更自然,更优雅.有没有人遇到过更好的方法来做到这一点,考虑到夏令时? 解决方法
您可以使用
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的评论. (谢谢) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |