views:

38

answers:

3

Using Ruby on Rails, I'm filling a 'select' with times using a given increment, such as every 30 minutes. Currently I'm writing out all the possibilities in a YAML file, but i feel like there's a slicker way. I'm thinking I want to provide a start_time, an end_time, an increment, and currently just one more option called 'Closed' (think 'business_hours'). So, my select might display:

'Closed'

5:00am

5:30am

6:00am

...

[all the way to]...

11:30pm

Can anyone think of a better way of doing this, or is just 'spelling' them all out the best way?

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

This answer is based on @emh answer.

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

You can use it this way:

create_hours(:start_time => 5.hours, :end_time => 23.hours + 5.minutes)
=> ["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"]

To add "Closed" use:

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

You can also pass :increment => 15.minutes - by default it is set to 30.minutes.

klew
A: 

Instead of a <select> you might consider using the HTML5 time input type:

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

Since the time input is only available in HTML5 (indeed, only Opera supports it so far), you'll want a way for other browsers to use it. I asked a question about doing the same thing for a <input type='range'> element.

James A. Rosen