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

后端 未结 5 954
误落风尘
误落风尘 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条回答
  •  闹比i
    闹比i (楼主)
    2021-02-07 13:25

    It's a little bit tricky, but not so hard to calculate.

    Use ActiveSupport::DateAndTimeCalculations#end_of_week to calculate end of a week, this method accepts a start_day parameter that is used to indicate start day of the week (it's :monday by default). They even have implemented sunday method.

    The trick is the following: if you want to calculate closest Monday, you may calculate it as a end of the week which starts on Tuesday (Tue => 1st day, Wed => 2nd day, ..., Mon => 7th day which is also end of the week).

    So all you need to do is:

    # it will return current date if today is Monday and nearest Monday otherwise
    Date.today.end_of_week(:tuesday) 
    

提交回复
热议问题