How to calculate next, previous business day in Rails?

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

How to calculate next and previous business days in Rails?

12条回答
  •  礼貌的吻别
    2021-02-08 09:33

    Here is a faster method that uses a simple calculation instead of iterating over the days.

    class Time
    
      def shift_weekdays(num_weekdays)
        base = self
    
        # corner case: self falls on a Sat or Sun then treat like its the next Monday
        case self.wday
          when 0
            base = self + 1.day
          when 6
            base = self + 2.day
        end
        day_of_week = base.wday - 1 # Monday is 0
    
        weekends = (day_of_week + num_weekdays) / 5
    
        base + (weekends*2).days + num_weekdays.days
      end
    
    end
    

    The method is on class Time but can be used on Date class as well.

提交回复
热议问题