【问题标题】:Creating select list in half-hour increments以半小时为增量创建选择列表
【发布时间】:2011-09-18 06:58:37
【问题描述】:

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

例如,如果我有这些值:

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

我使用什么 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>

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

任何指导将不胜感激。

【问题讨论】:

  • 我觉得你的数组想法很不错。成功了!
  • 我不会在这件事上矫枉过正。你可以用一个相当简单的算法来完成这个。我会看看我是否可以在下面的答案中写一个

标签: php select time


【解决方案1】:

我不知道你可以使用 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;
}

【讨论】:

  • 嗨,根据您的代码,我认为这是正确的方法。 $options = 数组(); foreach (range(0,23) as $fullhour) { $parthour = $fullhour > 12 ? $fullhour - 12 : $fullhour; $后缀 = $fullhour > 11 ? “下午”:“上午”; $options["$fullhour:00"] = $parthour.":00".$sufix; $options["$fullhour:30"] = $parthour.":30".$sufix;}
【解决方案2】:

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

考虑:

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

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

【讨论】:

  • 美丽。正是我正在拍摄的那种东西。格拉西亚斯。
  • 考虑一个更简单的脚本不需要调用 date 和 strtotime 会快得多(无论如何我在这里给了 +1)
  • 你可以把while写成for。如果您喜欢打高尔夫球:codepad.org/LcKmWheb
  • @Christopher - 简洁的解决方案! @yes123 - 用 C 语言将其作为 PHP 扩展编写会更快,而且还为时过早。
  • 如果该代码在 23:59:59 开始运行并开始新的一天会发生什么?
【解决方案3】:

这似乎也能产生你想要的东西..

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

【讨论】:

  • 你应该尽量避免在你的循环中计算。
  • 嗯,是的@PeeHaa,你没看错。但是 - 在像这样的循环中进行了几次简单的计算,清晰度可能远远超过对性能的影响。但是原则上应该把30*60换成1800。
  • 添加上午:下午时间的最佳答案。
【解决方案4】:

尝试使用此方法创建间隔为 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);

【讨论】:

    【解决方案5】:

    根据 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;
    }
    

    【讨论】:

    • 很好地抓住了错字。原文没有使用后缀变量。您可能还希望在开头包含options["0:00"]="12:00$am";options["0:30"]="12:30am";(并将范围调整为从 1 开始),以便更轻松地读取午夜时间。
    【解决方案6】:

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

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

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

    这个输出(截断)...

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

    【讨论】:

      【解决方案7】:

      另一种方法是通过使用 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);
      

      然后打印:

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

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

      【讨论】:

        【解决方案8】:
        <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>
        

        【讨论】:

        • 添加一些描述来回答。@Wewo Brian
        【解决方案9】:

        这是 12 小时上午/下午的解决方案:

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-09-23
          相关资源
          最近更新 更多