views:

520

answers:

3

how to calculate next, previous business day in rails.

A: 

Well, you can use something like yesterday = 1.days.ago to get yesterday's date. Use yesterday.strftime('%w') to get the day of the week as a integer (0=Sunday, 6=Saturday). If yesterday is 0 (Sunday), then the previous day of the week would be 3.days.ago ... you get the idea.

And you can use tomorrow = 1.days.since to get tomorrow's date.

Callmeed
+2  A: 

As far as I understand, this is what you are looking for? (tested it)

require 'date'
def next_business_day(date)
  skip_weekends(date, 1)
end    

def previous_business_day(date)
  skip_weekends(date, -1)
end

def skip_weekends(date, inc)
  date += inc
  while (date.wday % 7 == 0) or (date.wday % 7 == 6) do
    date += inc
  end   
  date
end

You can test it as follows:

begin
  t = Date.new(2009,9,11) #Friday, today
  puts "Today: #{Date::DAYNAMES[t.wday]} #{Date::MONTHNAMES[t.mon]} #{t.day}"
  nextday = next_business_day(t)
  puts "Next B-day: #{Date::MONTHNAMES[nextday.mon]} #{nextday.day}"
  previousday = previous_business_day(nextday)
  puts "back to previous: #{Date::MONTHNAMES[previousday.mon]} #{previousday.day}"
  yesterday = previous_business_day(previousday)
  puts "yesterday: #{Date::MONTHNAMES[yesterday.mon]} #{yesterday.day}"  
end
Felix Ogg