How to calculate next, previous business day in Rails?

前端 未结 12 2335
粉色の甜心
粉色の甜心 2021-02-08 08:43

How to calculate next and previous business days in Rails?

12条回答
  •  粉色の甜心
    2021-02-08 09:34

    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 = 1)
      date += inc
      while date.wday == 0 || date.wday == 6
        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  
    

提交回复
热议问题