Skip to content

Instantly share code, notes, and snippets.

@tejo
Created May 15, 2011 12:06
Show Gist options
  • Select an option

  • Save tejo/973089 to your computer and use it in GitHub Desktop.

Select an option

Save tejo/973089 to your computer and use it in GitHub Desktop.
business day between 2 date
(((calculate_working_days(20.days.ago ,Time.now, [0,6])/60)/60)/24).to_i
# 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
def business_days_ago(num,start_date=nil)
# takes the number of days in the past you are looking for
# like 10 business days ago
start_date ||= Date.today
start_day_of_week = start_date.cwday #Date.today.cwday
ans = 0
# find the number of weeks
weeks = num / 5.0
#puts "yields #{weeks} weeks"
temp_num = num > 5 ? 5 : num
#puts "first temp num #{temp_num}"
begin
ans += days_to_adjust(start_day_of_week,temp_num)
#puts "ans in loop #{ans}"
weeks -= 1.0
#puts "weeks in loop #{weeks}"
temp_num = (weeks >= 1) ? 5 : num % 5
#puts "temp_num after loop #{temp_num}"
end while weeks > 0
#puts "#{start_date} - #{num} - #{ans}"
days_ago = start_date - num - ans
end
def days_to_adjust(start_day_of_week,num)
ansr = 0
case start_day_of_week
when 1
if (1..5).include?(num) then ansr += 2 end
when 2
if (2..5).include?(num) then ansr += 2 end
when 3
if (3..5).include?(num) then ansr += 2 end
when 4
if (4..5).include?(num) then ansr += 2 end
when 5
if 5 == num then ansr += 2 end
when 6
# no adj
when 7
if (1..5).include?(num) then ansr += 1 end
end
return ansr
end
business_days_ago(5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment