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?
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)
=> ["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)
You can also pass :increment => 15.minutes
- by default it is set to 30.minutes
.
["closed"] + Array.new(24.hours / 30.minutes) do |i|
(Time.now.midnight + (i*30.minutes)).strftime("%I:%M %p")
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With