Reynier
Reynier

Reputation: 2478

CodeIgniter: TIME selector for forms

I'm trying to build a TIME selector for a CI project I'm working on but has not idea in how to deal with this. Since this will be use in a form for a shopping store open/close definition basically start hour should be 9AM and end hour should be 11PM. Now what I have think and done is created a array like this one:

  <?php
    $hour = array(
        "08:00 AM",
        "09:00 AM",
        "10:00 AM",
        "11:00 AM",
        "12:00 PM",
        "01:00 PM",
        "02:00 PM",
        "03:00 PM",
        "04:00 PM",
        "05:00 PM",
        "06:00 PM",
        "07:00 PM",
        "08:00 PM",
        "09:00 PM",
        "10:00 PM",
        "11:00 PM"
    );
    ?>

And then build a form_dropbox()using the form helper as you can see here:

<?php echo form_dropdown('starting_hour', $hour) ?>

This works and show what I want to show but the problem comes when I get the data in the script since I get the KEY for the choice I made. Then I think in add a key by myself but this time using MySQL right format for TIME type for example:

array("08:00" => "08:00 AM")

But this is ugly, how did you attack this? Any advice or help? Suggestions?

Upvotes: 0

Views: 1134

Answers (2)

Nouphal.M
Nouphal.M

Reputation: 6344

Try

$times = array();
$curTime = "07:00 AM";
for ($i = 0; $i < 16; $i++) {
  $strTime = strtotime($curTime);
  $ind = date('G',strtotime('+1 hours', $strTime));
  $times[$ind] =  date('h:i a',strtotime('+1 hours', $strTime)); 
  $curTime = date('g:i a',strtotime('+1 hours', $strTime));
}

Now you could take the array index in a 24 hour format.

Then you could try like

$ind = date('h:i_a',strtotime('+1 hours', $strTime));

instead of

$ind = date('G',strtotime('+1 hours', $strTime));

and then replace underscore with a space to get the time back.

Upvotes: 1

Kumar V
Kumar V

Reputation: 8830

In addition to Nouphal.M solution, You can keep this array in your controller private variable or config variable.

Then you can pass this array to view to show .

In $_POST action, you will get number (i.e key). Then you can get the time value from array wit use of key as $time[$key]

For ex: I'm going to keep this array in controller itself.

private $time_values;

add below code in constructor:

$times = array();
$curTime = "07:00 AM";
for ($i = 0; $i < 16; $i++) {
  $strTime = strtotime($curTime);
  $ind = date('G',strtotime('+1 hours', $strTime));
  $times[$ind] =  date('h:i a',strtotime('+1 hours', $strTime)); 
  $curTime = date('g:i a',strtotime('+1 hours', $strTime));
}
$this->time_values = $times;

To pass to view:

$data["hour"] = $this->time_values ;

In action:

$sel_time = $this->input->post("hour");

$sel_time_val = $this->time_values[$sel_time];

Upvotes: 1

Related Questions