在任何给定日期(包括将来)的X天外(例如5天)之后,如何计算第二天(例如,星期一)?

时间:2015-05-24 00:32:51

标签: ruby date datetime ruby-on-rails-4

一直在鼓吹我的头......

我目前的方法仅适用于过去的日期。如果start_date就像2个月后那样......它不起作用。

date_of_next_X_day_Y_days_out_from_Z_start("Monday", 5, Date.parse(May 23,2015))
# ==> June 1, 2015

date_of_next_X_day_Y_days_out_from_Z_start("Wednesday", 7, Date.parse(May 8,2015))
# ==> May 20, 2015

date_of_next_X_day_Y_days_out_from_Z_start("Friday", 3, Date.parse(June 15,2015))
# ==> June 19, 2015

我需要对此进行更新,以便对于任何start_date,无论是今天,五周前还是五天之后,我都可以找到下一个(星期几)至少(某一天)几天外出的天数。

例如

advance

仅供参考我确实有轨道,所以请随时与changevar tap = UITapGestureRecognizer(target: self, action: "handle:") view.addGestureRecognizer(tap) 助手大声喊叫。

4 个答案:

答案 0 :(得分:0)

在简单的Ruby中,我就是这样做的

def date_of_next_X_day_Y_days_out_from_Z_start(target_wday, skip, d)
  d += skip  # add "skip" number of days 

  # now keep add a day while checking wday (weekday) until we hit our target
  # 0 = Monday, ..., 6 = Sunday

  (0..6).each do |i|
    break if d.wday == target_wday
    d += 1
  end

  puts "Next Tuesday is #{d}"

使用示例:

# Find the next Tuesday (1) 5 days after June 15, 2015
date_of_next_X_day_Y_days_out_from_Z_start(1, 5, Date.parse("June 15,2015"))

答案 1 :(得分:0)

使用工作日作为数字(周日为0,星期六为6),您可以使用以下公式确定所需日期:

def date_of_next_X_day_Y_days_out_from_Z_start(wday, number_of_days, start_date)
  day_ahead = start_date + number_of_days.days
  (day_ahead) + ((7 - day_ahead.wday + wday) % 7).days
end

一些测试:

dates = [
  { wday: 1, n_days: 5, start_date: Date.parse('May 23,2015') },
  { wday: 3, n_days: 7, start_date: Date.parse('May 8,2015') },
  { wday: 5, n_days: 3, start_date: Date.parse('June 15,2015') },
  { wday: 3, n_days: 1, start_date: Date.parse('May 13,2015') },
  { wday: 5, n_days: 1, start_date: Date.parse('May 20,2015') }
]

dates.each do |date|
  puts date_of_next_X_day_Y_days_out_from_Z_start(date[:wday], date[:n_days], date[:start_date])
end

# => 2015-06-01
# => 2015-05-20
# => 2015-06-19
# => 2015-05-20
# => 2015-05-22

答案 2 :(得分:0)

这可能有效:

reset

答案 3 :(得分:0)

def next_date(target_wday, skip_num_days, start_date)

  date = Date.parse(target_wday)
  delta = date > start_date ? 0 : 7
  actual_next_day = date + delta 

  # define delta_2 so you're able to use += 
  delta_2 = 0

  # calculates how many weeks ahead the start date is
  repeat = (actual_next_day - start_date).to_i % 7

  # removes the current week you're calculating
  ( repeat - 1 ).times do 
    delta_2 += (actual_next_day - start_date) < skip_num_days ? 7 : 0
  end

  actual_next_day + delta_2
end 

使用您当前的方法,问题是您没有考虑到start_date date提前几周,所以您的返回日期不足。

您可以计算start_date前几周,并重复计算delta_2,同时不断向其中添加条件值。 delta_2现在将包括1)start_date提前几周,2)如果actual_next_day未达到要跳过的天数,则额外增加一周。