How to calculate next, previous business day in Rails?

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

How to calculate next and previous business days in Rails?

12条回答
  •  北荒
    北荒 (楼主)
    2021-02-08 09:14

    If you are running on rails, You could create a config/initializers/date_time.rb

    class DateTime
      def next_business_day
          # if its a friday saturday or sunday
        if self.day > 4
    
          # calculate the remaining days to add to the current day
          remaining_days = 7 - self.day + 1
    
          return remaining_days.days.from_now
        else
    
          # return tomorrow
          return self.tomorrow
        end
      end
    end
    

    usage:

    a = DateTime.now
    a.next_business_day
    => Mon, 08 Jun 2020 13:46:13 UTC +00:00
    

提交回复
热议问题