Baran
Baran

Reputation: 1118

Rails Time Select with two range

I have to show a select box which have time from 9 Am to 11 Am Then 1Pm to 3pm with 15 minutes inteveral like the following:

9:00 AM
9:15 AM
9:30 AM
.
.
.
10:45 AM
11:00 AM
01:00 PM
01:15 PM
01:30 PM
.
.
.
2:45 PM
3:00 PM

The above mentioned range will be dynamic but it has two intervals. Hows it is possible to achieve this?

Upvotes: 0

Views: 847

Answers (1)

Nitish Parkar
Nitish Parkar

Reputation: 2868

First define the boundaries,

start_time = DateTime.parse("9 AM").to_i
start_interval = DateTime.parse("11 AM").to_i
end_interval = DateTime.parse("1 PM").to_i
end_time = DateTime.parse("3 PM").to_i

Then use range and select to get the desired values,

values = (start_time..end_time).step(15.minutes).select{|t| t <= start_interval || t >= end_interval }

Then you can iterate over these values to generate select options, for example,

select_tag :dt, options_for_select(values.map{ |t| [ Time.at(t).utc.to_datetime.strftime("%H:%M %p"), Time.at(t).utc.to_datetime ] } )

You can try this in console,

> (start_time..end_time).step(15.minutes).select{|t| t <= start_interval || t >= end_interval }.map{ |t| Time.at(t).utc.to_datetime.strftime("%H:%M %p") }

=> ["09:00 AM", "09:15 AM", "09:30 AM", "09:45 AM", "10:00 AM", "10:15 AM", "10:30 AM", "10:45 AM", "11:00 AM", "13:00 PM", "13:15 PM", "13:30 PM", "13:45 PM", "14:00 PM", "14:15 PM", "14:30 PM", "14:45 PM", "15:00 PM"] 

Upvotes: 4

Related Questions