2013-04-03 23 views
0

我第一次在StackOverflow上作爲海報,通常只是一個瀏覽器,但是這次我遇到了一個問題。PHP +處理22:00到04:00之間的時間

我有一個腳本,它基於什麼時候設置某些變量。

<?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 & 14:00之間。

但是,當時間是23:30,並且它在22:00 & 02:00之間檢查時,它顯示「有一個藤壺!」

我在假設從22:00跳到02:00將腳本混淆爲02:00小於22:00?

不是最簡單的代碼或最好的方法,但想知道是否有人可以建議我如何克服這一點?

回答

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; 
0

只是胡亂猜測。您是否試圖在22:00 < - > 2:00條件之前移動最後一個條件(elseif),並使您的22:00條件僅限於一個條件 - >僅> 22:00(無< 2:00)

1

當使用日期,你應該總是使用對象來幫助你喜歡DateTime。這些對象將幫助您操縱日期並獲取時間戳。比較日期時,使用時間戳總是一個想法。

希望它有幫助。