Creating select list in half-hour increments

Viewed 30744

I have two variables: $start_time and $end_time. These values are times in 24 hour XX:XX format, and always end with either :00 or :30. They are supposed to define a range that determines times that appear in a drop-down select list in a HTML form, but the form displays the format in X:XX am/pm notation.

For example, if I have these values:

$start_time = "11:00";
$end_time   = "13:30";

What PHP code do I use to generate a select list which looks like this?

<option value="11:00">11:00 am</option>
<option value="11:30">11:30 am</option>
<option value="12:00">12:00 pm</option>
<option value="12:30">12:30 pm</option>
<option value="13:00">1:00 pm</option>
<option value="13:30">1:30 pm</option>

I know how to accomplish this by building an array of all possible values manually and then working backwards, but there must be a much more elegant way that uses PHP's built-in time functions.

Any guidance would be much appreciated.

9 Answers

Here is a solution for 12 hours with AM/PM:

<?php
$steps   = 15; // only edit the minutes value
$current = 0;
$loops   = 24*(60/$steps);

for ($i = 0; $i < $loops; $i++) {
    $hour = $i/(60/$steps);
    $time = sprintf('%02d:%02d %s', $hour, $current%60, intval($hour/12) == 0 ? ' AM' : ' PM');
    echo '<option>'.$time.'</option>';
    $current += $steps;
}
?>

And for 24 hours:

<?php
$steps   = 15; // only edit the minutes value
$current = 0;
$loops   = 24*(60/$steps);

for ($i = 0; $i < $loops; $i++) {
    $time = sprintf('%02d:%02d', $i/(60/$steps), $current%60);
    echo '<option>'.$time.'</option>';
    $current += $steps;
}
?>
Related