Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dropdown 24 hour option values and 12 hour display

Tags:

html

php

time

I need to create an array for time that I will use in a HTML dropdown. The array keys should be in 24 hour format and value in 12 hours with am and pm. In the database I want to store the 24h format. Is there a quick way to create the array instead of typing each hour?

example:

'00:00:00'  => '12:00am',
'01:00:00'  => '1:00am',
etc
like image 604
CyberJunkie Avatar asked Jun 11 '12 23:06

CyberJunkie


1 Answers

Use a loop:

<select>
<?php for($i = 0; $i < 24; $i++): ?>
  <option value="<?= $i; ?>"><?= $i % 12 ? $i % 12 : 12 ?>:00 <?= $i >= 12 ? 'pm' : 'am' ?></option>
<?php endfor ?>
</select>

This would ouput:

<select>
  <option value="0">12:00 am</option>
  <option value="1">1:00 am</option>
  <option value="2">2:00 am</option>
  <option value="3">3:00 am</option>
  <option value="4">4:00 am</option>
  <option value="5">5:00 am</option>
  <option value="6">6:00 am</option>
  <option value="7">7:00 am</option>
  <option value="8">8:00 am</option>
  <option value="9">9:00 am</option>
  <option value="10">10:00 am</option>
  <option value="11">11:00 am</option>
  <option value="12">12:00 pm</option>
  <option value="13">1:00 pm</option>
  <option value="14">2:00 pm</option>
  <option value="15">3:00 pm</option>
  <option value="16">4:00 pm</option>
  <option value="17">5:00 pm</option>
  <option value="18">6:00 pm</option>
  <option value="19">7:00 pm</option>
  <option value="20">8:00 pm</option>
  <option value="21">9:00 pm</option>
  <option value="22">10:00 pm</option>
  <option value="23">11:00 pm</option>
</select>
like image 177
Paul Avatar answered Nov 18 '22 03:11

Paul