How to calculate next and previous business days in Rails?
This is a method I use in my production scheduling script:
require 'date'
def shift_business_days(date, incr)
date = Date.parse(date.to_s)
incr.abs.times do
date += (incr < 0 ? -1 : 1)
while date.saturday? || date.sunday? do
date += (incr < 0 ? -1 : 1)
end
end
date
end
It takes a date and a positive or negative integer incr
as arguments, and increments or decrements the date by incr
days, skipping weekends. This has the added benefit of being able handle a Date/Time object or any date string that Date.parse can handle.
For example:
# (today is 2019-03-08)
shift_business_days(Time.now, 2)
##=> #
shift_business_days('5/20', -10)
##=> #