2017-05-20 85 views
0

12小時我現在有哪些填充這樣選擇列表中的增量時間由15分鐘與AM/PM

for($hours=0; $hours<24; $hours++) // the interval for hours is '1' 
for($mins=0; $mins<60; $mins+=15) // the interval for mins is '30' 
    echo '<option>'.str_pad($hours,2,'0',STR_PAD_LEFT).':' 
        .str_pad($mins,2,'0',STR_PAD_LEFT).'</option>'; 

目前填充

12:15 
12:30 
12:45 
13:00 
13:15 
13:30 
13:45 
14:00 
14:15 

這確實的工作選項選擇列表總共24小時增加15分鐘,但我需要使用AM/PM將其更改爲12小時。我不知道我該如何做到這一點。

所以我的結果應該是這樣的

11:30 AM 
11:45 AM 
12:00 PM 
12:15 PM 
12:30 PM 
12:45 PM 
01:00 PM 
01:15 PM... 

回答

1

懶惰的解決方案是檢查小時值和使用條件中減去12在適當的時候,以及AM/PM之間切換。那麼當然你需要另一個條件來處理12而不是00的特殊情況。雖然這會起作用,但它並不是特別優雅。

我建議的另一種方法是在幾秒鐘內建立15分鐘增量的數組,然後使用date()格式化輸出。

例子:

// 15 mins = 900 seconds. 
$increment = 900; 

// All possible 15 minute periods in a day up to 23:45. 
$day_in_increments = range(0, (86400 - $increment), $increment); 

// Output as options. 
array_walk($day_in_increments, function($time) { 
    printf('<option>%s</option>', date('g:i A', $time)); 
}); 

http://php.net/manual/en/function.date.php

+0

完美!我喜歡你如何在01:00進入01:00 –

0

您可以使用一個變量$a存儲AM/PM文本,並打印出來,如果$hours大於12

for($hours=0; $hours<24; $hours++) // the interval for hours is '1' 
{ 
    // add this line 
    if($hours<12) $a = 'AM' else {$a = 'PM'; $hours-=12;} 

    for($mins=0; $mins<60; $mins+=15) // the interval for mins is '30' 
     echo '<option>'.str_pad($hours,2,'0',STR_PAD_LEFT).':' 
       // and add this variable $a in the end of the line 
       .str_pad($mins,2,'0',STR_PAD_LEFT).$a.'</option>'; 

} 
0

試試看。

$start = '11:15'; 
$end = '24:15'; 

$tStart = strtotime($start); 
$tEnd = strtotime($end); 
$tNow = $tStart; 
while ($tNow <= $tEnd) { 
    echo '<option>' . date('h:i A', $tNow) . "</option>"; 
    $tNow = strtotime('+15 minutes', $tNow); 
} 

DEMO