問題描述
顯示兩個給定時間之間的 15 分鐘步長 (display 15‑minute steps between two given times)
I have an appointments table which saves 2 times. start and end. I want to display all appointments in 15 minute steps. e.g. given 10am /11am, now display me 10.15, 10.30, 10.45 in my view! Thx for advise!
‑@appointment.each do |form|
=form.date
=form.start_time
=form.end_time
‑‑‑‑‑
參考解法
方法 1:
I have an one‑liner, but is this what you really want? And hopefully the delta between this two dates isn't too big, the code below isn't very efficient.
(Time.now.to_i..1.hour.from_now.to_i).to_a.in_groups_of(15.minutes).collect(&:first).collect { |t| Time.at(t) }
Better solution:
# Your variables
time_start = Time.now
time_end = time_start + 1.hour
[time_start].tap { |array| array << array.last + 15.minutes while array.last < time_end }
I added to
to Ruby's Time
instance methods:
class Time
def to(to, step = 15.minutes)
[self].tap { |array| array << array.last + step while array.last < to }
end
end
so you end up with code like this:
time_start.to(time_end)
All three solutions will end in an array containing Time
objects of steps.
=> [2011‑07‑22 17:11:11 +0200, 2011‑07‑22 17:26:11 +0200, 2011‑07‑22 17:41:11 +0200, 2011‑07‑22 17:56:11 +0200, 2011‑07‑22 18:11:11 +0200]
方法 2:
you just need to pass option :minute_step => 15 to the input fields
(by daniel、Mario Uher、naren)