Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating select list in half-hour increments

Tags:

php

select

time

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.

like image 723
RuCh Avatar asked Jun 19 '11 20:06

RuCh


2 Answers

Fairly straightforward with a little strtotime() and date() magic:

Consider:

<?php
$start = "11:00";
$end = "13:30";

$tStart = strtotime($start);
$tEnd = strtotime($end);
$tNow = $tStart;

while($tNow <= $tEnd){
  echo date("H:i",$tNow)."\n";
  $tNow = strtotime('+30 minutes',$tNow);
}

Getting stuff properly formatted and output in tags is left as an exercise, see the docs for date().

like image 57
timdev Avatar answered Oct 04 '22 20:10

timdev


This seems to produce you what you want too..

$start=strtotime('10:00');
$end=strtotime('21:30');
for ($halfhour=$start;$halfhour<=$end;$halfhour=$halfhour+30*60) {
    printf('<option value="%s">%s</option>',date('H:i',$halfhour),date('g:i a',$halfhour));
}
like image 32
Bing Avatar answered Oct 04 '22 20:10

Bing