php 以半小时为增量创建选择列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6404845/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:16:47  来源:igfitidea点击:

Creating select list in half-hour increments

phpselecttime

提问by RuCh

I have two variables: $start_timeand $end_time. These values are times in 24 hour XX:XXformat, and always end with either :00or :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/pmnotation.

我有两个变量:$start_time$end_time。这些值是 24 小时XX:XX格式的时间,并且总是以:00或结尾:30。它们应该定义一个范围来确定出现在 HTML 表单的下拉选择列表中的时间,但表单以X:XX am/pm符号显示格式。

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?

我使用什么 PHP 代码来生成看起来像这样的选择列表?

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

我知道如何通过手动构建所有可能值的数组然后向后工作来实现这一点,但必须有一种更优雅的方式来使用 PHP 的内置时间函数。

Any guidance would be much appreciated.

任何指导将不胜感激。

回答by timdev

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

使用一点strtotime()date()魔法相当简单:

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

正确格式化内容并在标签中输出作为练习,请参阅 date() 的文档。

回答by Bing

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));
}

回答by Explosion Pills

I don't know that you can use php's date and time functions as those are more for handling specific times, but here is a more elegant solution in general:

我不知道你可以使用 php 的日期和时间函数,因为它们更多地用于处理特定时间,但这里有一个更优雅的解决方案:

$options = array();
foreach (range(0,24) as $fullhour) {
   $parthour = $fullhour > 12 ? $fullhour - 12 : $fullhour;
   $parthour .= $fullhour > 11 ? " pm" : " am";
   $options["$fullhour:00"] = $parthour;
   $options["$fullhour:30"] = $parthour;
}

回答by Ravindra

Try this to create array of time with 30 min interval. I have tested it.

试试这个来创建间隔 30 分钟的时间数组。我已经测试过了。

    $options = array(); $min30=array('00','30');
    foreach (range(0,23) as $fullhour) {
       $parthour = $fullhour > 12 ? $fullhour - 12 : $fullhour;
        foreach($min30 as $int){
            if($fullhour > 11){
                $options[$fullhour.".".$int]=$parthour.":".$int." PM";
            }else{
                if($fullhour == 0){$parthour='12';}
                $options[$fullhour.".".$int]=$parthour.":".$int." AM" ;
            }
        }
    }
    print_r($options);

回答by Peter

A different approach could be to completely solve your issue using PHP by using the DateTime object:

一种不同的方法可能是通过使用 DateTime 对象使用 PHP 完全解决您的问题:

// Make a DateTime object with the current date and time
$today = new DateTime();

// Make an empty array to contain the hours
$aHours = array();

// Make another DateTime object with the current date and time
$oStart = new DateTime('now');

// Set current time to midnight
$oStart->setTime(0, 0);

// Clone DateTime object (This is like 'copying' it)
$oEnd = clone $oStart;

// Add 1 day (24 hours)
$oEnd->add(new DateInterval("P1D"));

// Add each hour to an array
while ($oStart->getTimestamp() < $oEnd->getTimestamp()) {
    $aHours[] = $oStart->format('H');
    $oStart->add(new DateInterval("PT1H"));
}

// Create an array with halfs
$halfs = array(
    '0',
    '30',
);

// Get the current quarter
$currentHalf = $today->format('i') - ($today->format('i') % 30);

Then to print:

然后打印:

<select name="" id="">
    <option value="-1">Choose a time</option>
    <?php foreach ($aHours as $hour): ?>
        <?php foreach ($halfs as $half): ?>
            <option value="<?= sprintf("%02d:%02d", $hour, $half); ?>" <?= ($hour == $today->format('H') && $half == $currentHalf) ? 'selected' : ''; ?>>
                <?= sprintf("%02d:%02d", $hour, $half); ?>
            </option>
        <?php endforeach; ?>
    <?php endforeach; ?>
</select>

In the above example you will generate a dropdown with all hours of a day. The current hour and half hour will be automatically selected.

在上面的示例中,您将生成一个包含一天中所有小时的下拉列表。将自动选择当前小时和半小时。

回答by Wewo Brian

<select>
  <?php
     $h = 0;
     $m = 0;
     while ($h != 24.5) {
       if(strpos($h,".") !== false){
           $v = ($h-0.5).'30';
       }else{
           $v = $h.'00';
       }
       if ($h < 10) {
           $v = '0'.$v;
       }
       echo '<option>'.$v.'</option>';

       $h = $h + 0.5;
     }
  ?>
</select>

回答by Hank Frinkel

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

这是 12 小时 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:

以及 24 小时:

<?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;
}
?>

回答by Edgar Nadal

Based on Explosion Pills code, i think this is the correct way.

基于 Explosion Pills 代码,我认为这是正确的方法。

$options = array();
foreach (range(0,23) as $fullhour) 
{
    $parthour = $fullhour > 12 ? $fullhour - 12 : $fullhour;
    $sufix = $fullhour > 11 ? " pm" : " am";

    $options["$fullhour:00"] = $parthour.":00".$sufix;
    $options["$fullhour:30"] = $parthour.":30".$sufix;
}

回答by ssaltman

This is a full working version and I'm using it (modified from above). The change I made was have the value of the option tag formatted for entry into a sql db. I also changed 00:00 to midnight and 12:00 to noon.

这是一个完整的工作版本,我正在使用它(从上面修改)。我所做的更改是将选项标记的值格式化为进入 sql 数据库。我也将 00:00 更改为午夜,将 12:00 更改为中午。

(Edited again to show selection option)

(再次编辑以显示选择选项)

<select name="starttime">
<?php 
foreach (range(0,23) as $fullhour) {
$fullhour2digit = strlen($fullhour)==1 ? '0' . $fullhour : $fullhour;
$parthour = $fullhour > 12 ? $fullhour - 12 : $fullhour;
$parthour .= $fullhour > 11 ? ":00 pm" : ":00 am";
$parthour = $parthour=='0:00 am' ? 'midnight' : $parthour;
$parthour = $parthour=='12:00 pm' ? 'noon' : $parthour;

$parthalf = $fullhour > 12 ? $fullhour - 12 : $fullhour;
$parthalf .= $fullhour > 11 ? ":30 pm" : ":30 am";


//SHOWS THE TEST FOR 'SELECTED' IN THE OPTION TAG
     echo '<option ';
     if (date("H:i:s", strtotime($startdate)) === $fullhour2digit . ':00:00')
        {echo ' SELECTED ';}
     echo 'value="' . $fullhour2digit . ':00:00">' .  $parthour . '</option>';
     echo '<option ';
     if (date("H:i:s", strtotime($startdate)) === $fullhour2digit  . ':30:00')
        {echo ' SELECTED ';}
     echo 'value="' . $fullhour2digit . ':30:00">' .  $parthalf . '</option>';
}
?>
</select>

This outputs (truncated)...

此输出(截断)...

<select name="starttime">
<option value="00:00:00">midnight</option><option value="00:30:00">0:30 am</option>
 ....