获取最近n天的日期

时间:2016-05-12 09:51:28

标签: ruby date

我尝试实现方法,返回最近n天的日期集合,例如星期一。

我的方法:

PRODUCT

我不知道如何正确修复此方法。你可以帮帮我吗? 提前谢谢。

我对回报的预测:

选择代码:

  def date_of_next(day, weeks)
    date = Date.parse(day)
    if date > Date.today
      delta = 0
      date + delta
    else
      (0..weeks.to_i).each do |i|
        delta = 7 * i
        date + delta
      end
    end
  end

结果:

= f.select :date_of_training, label: "Data",
  collection: @trainer.work_schedules.map{ |tw| [tw.next_n_days(4, "Monday"), tw.id]},
  prompt: "Wybierz datę"

1 个答案:

答案 0 :(得分:1)

天真的实施:

def next_n_days(amount, day_of_week)
  (Date.today...Date.today+7*amount).select do |d|
    d.wday == day_of_week
  end
end

#     three ⇓  ⇓ Fridays
next_n_days 3, 5
#⇒ [
#   [0] #<Date: 2016-05-13 ((2457522j,0s,0n),+0s,2299161j)>,
#   [1] #<Date: 2016-05-20 ((2457529j,0s,0n),+0s,2299161j)>,
#   [2] #<Date: 2016-05-27 ((2457536j,0s,0n),+0s,2299161j)>
# ]

更准确的实施:

def next_n_days(amount, day_of_week)
  nearest = (Date.today...Date.today+7).detect { |d| d.wday == day_of_week }
  nearest.step(nearest+7*amount-1, 7).to_a
end