Ruby Business Days ago

written by justin on May 7th, 2008 @ 08:57 AM

My attempt at writing a solution to finding the number of business days ago from a specific date. I am using this in a Rails App.


    1 def business_days_ago(num,start_date=nil)
    2   # takes the number of days in the past you are looking for
    3   # like 10 business days ago
    4   start_date ||= Date.today
    5   start_day_of_week = start_date.cwday #Date.today.cwday
    6   ans = 0
    7   # find the number of weeks
    8   weeks = num / 5.0
    9   #puts "yields #{weeks} weeks"
   10 
   11   temp_num = num > 5 ? 5 : num
   12   #puts "first temp num #{temp_num}"
   13 
   14   begin
   15 
   16     ans += days_to_adjust(start_day_of_week,temp_num)
   17     #puts "ans in loop #{ans}"
   18 
   19     weeks -= 1.0
   20     #puts "weeks in loop #{weeks}"
   21 
   22     temp_num = (weeks >= 1) ? 5 : num % 5
   23     #puts "temp_num after loop #{temp_num}"
   24   end while weeks > 0
   25 
   26   #puts "#{start_date} - #{num} - #{ans}"
   27   days_ago = start_date - num - ans
   28 
   29 end
   30 
   31 
   32 
   33 def days_to_adjust(start_day_of_week,num)
   34   ansr = 0
   35   case start_day_of_week
   36   when 1
   37     if (1..5).include?(num) then ansr += 2 end
   38   when 2
   39     if (2..5).include?(num) then ansr += 2 end
   40   when 3
   41     if (3..5).include?(num) then ansr += 2 end
   42   when 4
   43     if (4..5).include?(num) then ansr += 2 end
   44   when 5
   45     if 5 == num then ansr += 2 end
   46   when 6
   47     # no adj
   48   when 7
   49     if (1..5).include?(num) then ansr += 1 end
   50   end
   51   return ansr
   52 end

Post a comment