2
votes

I'm having a date calculation problem, which is confusing my logic.

I have an application that accepts debit payments to a bank account, this charge must be generated at least three days before the day to be billed.

I need to pick up the next tenth day of the month, which may be the current month or the next month, depending on the current day.

For example, today is October 7, I need to get the next day 10, as long as starting today has an interval of three days, in this case I need to be returned October 10.

But if today is October 8, I need to pick up the next 10, in which case I need to be returned November 10.

What is the best solution to do this in Ruby?

3
"But if today is October 8, I need to pick up the next 10" -> do you mean "But if today is October 18, I need to pick up the next 10", i.e. a day > 10?koffeinfrei
@koffeinfrei, no... I need 3 days interval before generate, so if today is october 08, I need november 10Denis Gubaua

3 Answers

4
votes

Another option:

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"

To work require 'date'

3
votes

You could use something like this:

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"
3
votes

You can make use of a lazy enumerator in ruby to find the next valid day, starting today.

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