[英]Select list increment time by 15 minutes by 12 hour with AM/PM
I currently have a select list which populated options like this 我目前有一个选择列表,其中填充了这样的选项
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>';
Which currently populates 目前正在填充
12:15
12:30
12:45
13:00
13:15
13:30
13:45
14:00
14:15
which does the job of incrementing by 15 minutes for a total of 24 hours but I need to change this to 12 hours with AM/PM. 它可以将15分钟的增量总共增加24小时,但是我需要使用AM / PM将其更改为12小时。 I am not sure how I can do this. 我不确定该怎么做。
So my result should look like this 所以我的结果应该像这样
11:30 AM
11:45 AM
12:00 PM
12:15 PM
12:30 PM
12:45 PM
01:00 PM
01:15 PM...
The lazy solution would be to check the hour value and use a conditional to subtract 12 when appropriate as well as toggle between AM/PM. 懒惰的解决方案是检查小时值,并在适当时使用条件值减去12以及在AM / PM之间切换。 Then of course you need another conditional to handle the special case of 12 instead of 00. While this would work it's not particularly elegant. 然后,当然,您需要另一个条件来处理12而不是00的特殊情况。虽然这可以工作,但并不是特别优雅。
The alternative I would propose is to build an array of 15 minute increments in seconds and then format the output using date()
. 我建议的替代方法是建立一个以秒为单位的15分钟增量数组,然后使用date()
格式化输出。
Example: 例:
// 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 http://php.net/manual/zh/function.date.php
You can use a variable $a
to store the AM/PM text and print it out if the $hours
is greater than 12. 您可以使用变量$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>';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.