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.
Business days are the weekdays Monday through Friday. Check Business Days Only to exclude weekend days in your calendar calculation. Check Saturday is a Business Day to include Saturdays. Holidays are not included in the calculation.
The Excel NETWORKDAYS function calculates the number of working days between two dates. NETWORKDAYS automatically excludes weekends (Saturday and Sunday) and can optionally exclude a list of holidays supplied as dates.
Then, to calculate the number of business days in the specified time period, type the formula =NETWORKDAYS(B3,B4), where B3 is the starting date and B4 is the ending date.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With