在两个给定时间之间显示15分钟的步数

我有一个约会表,可以节省2次。 开始和结束。 我想以15分钟的步骤显示所有约会。 例如,上午10点/上午11点,现在在我的视图中显示10.15,10.30,10.45! 感谢建议!

-@appointment.each do |form| =form.date =form.start_time =form.end_time 

我有一个单行,但这是你真正想要的吗? 并且希望这两个日期之间的差异不是太大,下面的代码效率不高。

 (Time.now.to_i..1.hour.from_now.to_i).to_a.in_groups_of(15.minutes).collect(&:first).collect { |t| Time.at(t) } 

更好的方案:

 # 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 } 

我添加to Ruby的Time实例方法:

 class Time def to(to, step = 15.minutes) [self].tap { |array| array << array.last + step while array.last < to } end end 

所以你最终得到这样的代码:

 time_start.to(time_end) 

所有三个解决方案都将以包含Time对象步骤的数组结束。

  => [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] 

你只需要将选项:minute_step => 15传递给输入字段