Calculate number of business days between two days

date, ruby, ruby-on-rails

Solution

Take a look at business_time. It can be used for both the things you're asking.

Calculating business days between two dates:

wednesday = Date.parse("October 17, 2018")
monday = Date.parse("October 22, 2018")
wednesday.business_days_until(monday) # => 3

Adding business days to a given date:

4.business_days.from_now
8.business_days.after(some_date)

Historical answer

When this question was originally asked, `business_time` didn't provide the `business_days_until` method so the method below was provided to answer the first part of the question.

This could still be useful to someone who didn't need any of the other functionality from `business_time` and wanted to avoid adding an additional dependency.

def business_days_between(date1, date2)
  business_days = 0
  date = date2
  while date > date1
   business_days = business_days + 1 unless date.saturday? or date.sunday?
   date = date - 1.day
  end
  business_days
end

This can also be fine tuned to handle the cases that Tipx mentions in the way that you would like.

Problem

I need to calculate the number of business days between two dates. How can I pull that off using Ruby (or Rails...if there are Rails-specific helpers). Likewise, I'd like to be able to add business days to a given date. So if a date fell on a Thursday and I added 3 business days, it would return the next Tuesday.

Original source