Filling the selection in steps of several times, as well as additional parameters

Using Ruby on Rails, I populate the "select" times using this increment, for example every 30 minutes. I am currently writing all the features in a YAML file, but I feel that there is an easier way. I think I want to provide start_time, end_time, increment, and currently another option called Closed (think business_hours). So my choice can display:

'Closed'

5 a.m.

5:30 a.m.

6:00 AM

...

[all the way] ...

11:30 pm

Can anyone think of a better way to do this, or just “put” them on a better way?

+5
3

@emh.

def create_hours(parameters)
  start_time = parameters[:start_time] ? parameters[:start_time] : 0
  end_time = parameters[:end_time] ? parameters[:end_time] : 24.hours
  increment = parameters[:increment] ? parameters[:increment] : 30.minutes
  Array.new(1 + (end_time - start_time)/increment) do |i|
    (Time.now.midnight + (i*increment) + start_time).strftime("%I:%M %p")
  end
end

:

create_hours(:start_time => 5.hours, :end_time => 23.hours)
=> ["05:30 AM", "06:00 AM", "06:30 AM", "07:00 AM", "07:30 AM", "08:00 AM", 
    "08:30 AM", "09:00 AM", "09:30 AM", "10:00 AM", "10:30 AM", "11:00 AM", 
    "11:30 AM", "12:00 PM", "12:30 PM", "01:00 PM", "01:30 PM", "02:00 PM", 
    "02:30 PM", "03:00 PM", "03:30 PM", "04:00 PM", "04:30 PM", "05:00 PM", 
    "05:30 PM", "06:00 PM", "06:30 PM", "07:00 PM", "07:30 PM", "08:00 PM", 
    "08:30 PM", "09:00 PM", "09:30 PM", "10:00 PM", "10:30 PM", "11:00 PM"]

"" :

["closed"] + create_hours(:start_time => 5.hours, :end_time => 23.hours)

:increment => 15.minutes - 30.minutes.

+13
["closed"] + Array.new(24.hours / 30.minutes) do |i|
  (Time.now.midnight + (i*30.minutes)).strftime("%I:%M %p")
end
+8

Instead, <select>you can use the HTML5 input type time:

<input type='time' min='05:30' max='23:30' step='00:30' />

Since the input timeis only available in HTML5 (in fact, only Opera still supports it), you need other browsers to use it. I asked question to do the same for the item <input type='range'>.

0
source

All Articles