Rails: Is there away to get the Date object that is the closest Monday to today?

后端 未结 5 920
误落风尘
误落风尘 2021-02-07 12:54

Given a date, how do I find the nearest Monday in Rails?

I know I can do things like:

Date.tomorrow Date.today

Is there something like Date.nearest :mond

5条回答
  •  有刺的猬
    2021-02-07 13:09

    Untested, so you might need to finetune, but here you go:

    def Date.nearest_monday
      today = Date.today
      wday  = today.wday
      if wday > 4 # over the half of the week
        today + (7 - wday) # next monday
      else
        today - (1 + wday) # previous monday
      end
    end 
    

提交回复
热议问题