0

I have an app which is used to calculate the paychecks of a number of employees.

The paychecks are calculated from the 21st in a month to the 20th in the next month. So when the employee uses the app I need to find these two dates (start_date and end_date) based on the date today.

How can I do that? Something like beginning_of_month + 21 doesn't work because when it's the 3rd in a month it's beginning_of_last_month..

Any simple way to find the last 21st date and the next 20th date ?

Paul Brit
  • 5,901
  • 4
  • 22
  • 23
Twiddr
  • 297
  • 1
  • 4
  • 18

1 Answers1

2

You could create a helper method that could look something like this:

def paycheck_dates(date, past_day, future_day)
    before, after = Date.civil(date.year, date.month, past_day), Date.civil(date.year, date.month, future_day)
    before <<= 1 if before > date
    after >>= 1 if after < date
    return before, after
end

The operator <<= substracts a month, and >>= adds a month. In your case you could call this method like this:

current_date = Date.today
past_date, future_date = paycheck_dates(current_date, 21, 20)
Nobita
  • 23,519
  • 11
  • 58
  • 87