PHP +处理22:00至04:00之间的时间

时间:2013-04-03 13:04:23

标签: php date if-statement time

我第一次将StackOverflow作为海报,通常只是一个浏览器,但这次我自己遇到了一个问题。

我有一个脚本根据时间设置某些变量。

<?php
// Sunday
if( in_array($day, array(Sun)) ){
echo 'Conditions = Day:' . $day . ' ' . 'Time: ' . $current_time;
if (($current_time >= '06:01') && ($current_time <= '10:00')) {
    $stime = '06:00';
    $etime = '10:00';
    $showname = 'Dimitri Jegels';
 $image = 'images/placeholder/on-air.jpg';
//  echo $stime . ' and' . $etime . ' & ' . $showname . ' & ' . $image;
} elseif (($current_time >= '10:01') && ($current_time <= '14:00')) {
    $stime = '10:00';
    $etime = '14:00';
    $showname = 'Benito Vergotine';
 $image = 'images/placeholder/on-air.jpg';
//  echo $stime . ' and' . $etime . ' & ' . $showname . ' & ' . $image;
} elseif (($current_time >= '14:01') && ($current_time <= '18:00')) {
    $stime = '14:00';
    $etime = '18:00';
    $showname = 'Gavin Arends';
 $image = 'images/placeholder/on-air.jpg';
//  echo $stime . ' and' . $etime . ' & ' . $showname . ' & ' . $image;
} elseif (($current_time >= '18:01') && ($current_time <= '22:00')) {
    $stime = '18:00';
    $etime = '22:00';
    $showname = 'Tracy Lange';
 $image = 'images/placeholder/on-air.jpg';
//  echo $stime . ' and' . $etime . ' & ' . $showname . ' & ' . $image;
} elseif (($current_time >= '22:01') && ($current_time <= '02:00')) {
    $stime = '22:00';
    $etime = '02:00';
    $showname = 'Mehboob Bawa';
 $image = 'images/placeholder/on-air.jpg';
//  echo $stime . ' and' . $etime . ' & ' . $showname . ' & ' . $image;
} elseif (($current_time >= '02:01') && ($current_time <= '06:00')) {
    $stime = '02:00';
    $etime = '06:00';
    $showname = 'Training Slot';
 $image = 'images/placeholder/on-air.jpg';
//  echo $stime . ' and' . $etime . ' & ' . $showname . ' & ' . $image;
} else {
    $stime = '??:??';
    $etime = '??:??';
    $showname = 'There is a barnacle!';
}
}
?>

脚本工作正常,例如13:00,它在10:00和10:00之间检查。 14:00。

然而,当时间是23:30并且它在22:00和22:00之间检查。 02:00它显示“有一个藤壶!”

我假设从02:00到02:00的跳转会在02:00小于22:00时混淆脚本?

不是最整洁的代码或最佳方法,但想知道是否有人可以建议我如何克服这个问题?

4 个答案:

答案 0 :(得分:1)

您可以对此特殊情况使用OR条件:

} elseif (($current_time >= '22:01') || ($current_time <= '02:00')) {

但正如您已经提到的,您的代码不是很干净!

也许这会更好一点:

$names = array('Mehboob Bawa', 'Training Slot', 'Dimitri Jegels', 'Benito Vergotine', 'Gavin Arends', 'Tracy Lange');
$hours = getdate()["hours"];
$interval = (int)((($hours + 2) % 24) / 4);
$showname = $name[$interval];
$image = 'images/placeholder/on-air.jpg'; // can be also done via an array, if not always the same
$stime = ($interval * 4 + 22) % 24;
$etime = ($interval * 4 + 2) % 24;

答案 1 :(得分:1)

使用日期时,您应始终使用对象来帮助您DateTime。这些对象将帮助您操纵日期并获取时间戳。比较日期时,使用时间戳总是一个想法。

希望它有所帮助。

答案 2 :(得分:0)

您应该使用mktime转换时间,之后您可以检查时间是否大于其他时间,请检查http://php.net/manual/en/function.mktime.php

答案 3 :(得分:0)

只是一个疯狂的猜测。您是否尝试在22:00&lt; - &gt; 2:00条件之前移动最后一个条件(elseif),并且仅使用一个cond使您的22:00条件 - >仅> 22:00(不包括&lt; 2:00)