Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate number of business days between two days

Tags:

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.

like image 339
Shpigford Avatar asked Oct 26 '10 20:10

Shpigford


People also ask

How do you calculate business days?

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.

How do I calculate working days between two dates in Excel?

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.

Is there an Excel formula to calculate business days?

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.


1 Answers

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.

like image 90
mikej Avatar answered Nov 07 '22 05:11

mikej