Calculate the number of working days between two dates
Posted by Sandro Paganotti in
Ruby on Rails -
comments are closed
The Ruby api documentation is really useful, not only to find and understand Ruby methods and classes, but also for the amazing examples that sometimes you can find there. Yesterday I was looking for a method inside the Date class and I found a really useful piece of code in this page. With just a little effort I created a method that let you find the number of working days between two dates:
# wdays is an array with the days of the week
# to exclude (eg: [0,6] for sunday and saturday )
def calculate_working_days(d1,d2,wdays)
diff = d2 - d1
holidays = 0
ret = (d2-d1).divmod(7)
holidays = ret[0].truncate * wdays.length
d1 = d2 - ret[1]
while(d1 <= d2)
if wdays.include?(d1.wday)
holidays += 1
end
d1 += 1
end
diff - holidays
end


Comments
Edoc
Posted on January 30
Russell Tracey
Posted on January 31
Eric I.
Posted on January 31
That's a nice solution -- much better than those that iterate over every day in the range.
But it's not obvious to me what purpose sortding the wday array serves. And the block passed to the sort method seems redundant, as it implements the behavior sort would use if no block were passed, no?
Best,
Eric
Sandro Paganotti
Posted on January 31
Edoc
Posted on February 01