如何选择下个月的 10 号 ruby

How to pick the next 10th of the month ruby

我遇到了日期计算问题,这让我的逻辑很混乱。

我有一个接受银行账户借记付款的应用程序,这笔费用必须至少在开票前三天产生。

我需要取下一个月的十号,可能是当月也可能是下月,具体取决于当天。

比如今天是10月7日,我需要得到第二天的10,只要从今天开始有三天的间隔,那么我需要返回10月10日。

但是如果今天是10月8日,我需要取下10个,那么我需要在11月10日返回。

在 Ruby 中执行此操作的最佳解决方案是什么?

您可以在 ruby 中使用 lazy enumerator 来查找从今天开始的下一个有效日期。

(Date.today..Date::Infinity.new)
  .lazy
  .find { |date| date.day == 7 }
  .next_day(3)

你可以使用这样的东西:

def next_10th(date)
  year, month, day = date.year, date.month, date.day

  month += 1 if day > 7
  year += 1 if month > 12

  Date.new(year, (month - 1) % 12 + 1, 10)
end

next_10th(Date.new(2017, 11, 7)).to_s
#=> "2017-11-10"

next_10th(Date.new(2017, 11, 8)).to_s
#=> "2017-12-10"

next_10th(Date.new(2017, 11, 10)).to_s
#=> "2017-12-10"

next_10th(Date.new(2017, 12, 8)).to_s
#=> "2018-01-10"

另一个选项:

def next_10th_deadline_from date
  deadline = Date.new(date.year, date.month, 10)
  deadline = deadline.next_month if (deadline - date) < 3
  deadline
end


或者如果输入字符串和输出字符串:

def next_10th_deadline_from date
  date = Date.parse date
  deadline = Date.new(date.year, date.month, 10)
  deadline = deadline.next_month if (deadline - date) < 3
  deadline.to_s
end

next_10th_deadline_from '2018-12-07' #=> "2018-12-10"
next_10th_deadline_from '2018-12-08' #=> "2019-01-10"

上班require 'date'