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

后端 未结 5 953
误落风尘
误落风尘 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:06

    The commercial method on the Date object will let you do this. This example will get you the next Monday.

    Date.commercial(Date.today.year, 1+Date.today.cweek, 1)
    

    If you need the next or previous Monday, whichever is closest, you can do:

    Date.commercial(Date.today.year, Date.today.cwday.modulo(4)+Date.today.cweek, 1)
    

    I can't execute this right now, so forgive me if there are syntax errors.

提交回复
热议问题