Rails Time选择两个范围

时间:2014-10-12 07:29:06

标签: ruby-on-rails ruby ruby-on-rails-3

我必须显示一个选择框,其时间从上午9点到11点然后是1Pm到下午3点,其中15分钟如下:

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

上述范围将是动态的,但它有两个间隔。怎么可能实现这个目标?

1 个答案:

答案 0 :(得分:4)

首先定义边界,

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

然后使用rangeselect获取所需的值

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

然后,您可以迭代这些值以生成选择选项,例如

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 ] } )

您可以在控制台中尝试此操作,

> (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"]