How to calculate next, previous business day in Rails?

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

How to calculate next and previous business days in Rails?

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

    I realise that this is an old thread, but I just had to work this one out for myself and I was looking for a very short bit of code that was trivial to modify if a business had weird opening days (like "closed Sunday/Monday").

    def next_business_day(from_day)
      workdays = [1,2,3,4,5,6]
      test_day = from_day + 1.day
      return workdays.include?(test_day.wday) ? test_day : next_business_day(test_day)
    end
    

    I suppose it could be shortened again to something like this, but I think it becomes less obvious

    def next_business_day(from_day)
      test_day = from_day + 1.day
      [1,2,3,4,5,6].include?(test_day.wday) ? test_day : next_business_day(test_day)
    end
    

提交回复
热议问题