2016-11-24 179 views
0

我想創建一個下拉菜單,將當前時間作爲開始時間,並且最終會持續到24小時,就像直到24小時之後一樣,它會顯示每15分鐘增量的時間。問題是,當我嘗試運行循環開始時間是好的,但下一個循環時間跳轉到6小時後。循環內增加時間15分鐘

這裏是我的代碼:

$current_time = date('h:i A'); 
$end_hour  = date("+24 hours", $current_time); 

echo "<option>" . $current_time . "</option>"; 
for($i = 0; $i <= 96; $i++) { 
    echo "<option>" . date("h:i A", $tNow) . "</option>"; 
    $tNow = strtotime('+15 minutes',$current_time); 
} 

輸出來作爲 下午11時08 4:00 PM 4:15 PM 4:30 PM

等。

回答

3

您可以使用DateTime爲:

$now = new DateTime(); 
$end = clone $now; 
$end->modify("+24 hours"); 

while ($now <= $end) { 
    echo "<option>" . $now->format('h:i A'). "</option>"; 
    $now->modify('+15 minutes'); 
} 
+0

greta它爲我工作,但什麼是克隆? –

+0

使用[clone](http://php.net/manual/en/language.oop5.cloning.php),您可以複製實例化對象而不保留引用,因此對克隆對象所做的任何更新都不會影響原始一。 –

0

有幾件事。首先在你的第一行你缺少第二個參數。那麼你正在使用$ tNow未定義。

$current_time = date('h:i A', time()); 
$end_hour  = date("+24 hours", strtotime($current_time)); 


$tNow = strtotime($current_time); 
echo "<option>" . $current_time . "</option>"; 
for($i = 0; $i <= 96; $i++) { 
    echo "<option>" . date("h:i A", $tNow) . "</option>"; 
    $tNow = strtotime('+15 minutes', $tNow); 
} 
+0

第二個參數是可選。如果沒有給出,則使用當前日期。 –

+0

@Matei Mihai謝謝你忘記了! – Gacci