How to calculate next, previous business day in Rails?

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

How to calculate next and previous business days in Rails?

12条回答
  •  萌比男神i
    2021-02-08 09:15

    This is a method I use in my production scheduling script:

    require 'date'
    def shift_business_days(date, incr)
      date = Date.parse(date.to_s)
      incr.abs.times do
        date += (incr < 0 ? -1 : 1)
        while date.saturday? || date.sunday? do
          date += (incr < 0 ? -1 : 1)
        end
      end
      date
    end
    

    It takes a date and a positive or negative integer incr as arguments, and increments or decrements the date by incr days, skipping weekends. This has the added benefit of being able handle a Date/Time object or any date string that Date.parse can handle. For example:

    # (today is 2019-03-08)
    shift_business_days(Time.now, 2)
    ##=> #
    
    shift_business_days('5/20', -10)
    ##=> #
    

提交回复
热议问题