简体   繁体   中英

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. 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. 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.

The alternative I would propose is to build an array of 15 minute increments in seconds and then format the output using 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

Try it out.

$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

You can use a variable $a to store the AM/PM text and print it out if the $hours is greater than 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>';

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM