Php 用AM/PM选择列表以15分钟乘以12小时的增量时间

Php 用AM/PM选择列表以15分钟乘以12小时的增量时间,php,Php,我目前有一个选择列表,其中填充了如下选项 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

我目前有一个选择列表,其中填充了如下选项

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>';
11:30 AM
11:45 AM
12:00 PM
12:15 PM
12:30 PM
12:45 PM
01:00 PM
01:15 PM...
它的工作是增加15分钟,总共24小时,但我需要在上午/下午将其更改为12小时。我不知道我怎样才能做到这一点

所以我的结果应该是这样的

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>';
11:30 AM
11:45 AM
12:00 PM
12:15 PM
12:30 PM
12:45 PM
01:00 PM
01:15 PM...

如果
$hours
大于12,则可以使用变量
$a
存储AM/PM文本并将其打印出来

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

}
对于($hours=0;$hours试试看

$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);
}
$start='11:15';
$end='24:15';
$tStart=strottime($start);
$tEnd=STROTIME($end);
$tNow=$tStart;

而($tNow懒惰的解决方案是检查小时值,并在适当时使用条件减去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 ) );
} );
//15分钟=900秒。
$increment=900;
//在23:45之前,一天中所有可能的15分钟时段。
$day_增量=范围(0,(86400-$increment),$increment);
//输出为选项。
数组\u walk($day\u,增量,函数($time){
printf('%s',日期('g:ia',$time));
} );

太好了!我喜欢你将01:00改为1:00的方式,这太棒了……但我不明白为什么我的列表从晚上7:00开始???@JonnyO,我猜这是因为时区偏移。我今天可能会以不同的方式处理同一问题,所以我会更新我的答案以反映这一点。同时,查看文档中的日期:你可以使用<代码> DATEYDeFultTimeZONZONETSET(但一定要考虑可能产生的影响。@ Nathan Dawson完全正确。我有一个巨大的脑屁,认为我提前19个小时而不是落后5个小时。只需改变时区,然后在脚本末尾回到应用时区。工作完美。