17

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 :monday ?

1
  • 2
    do you need to go in both directions? i.e. if it is tuesday, go to yesterday but if it is friday go to the next monday?
    – zsalzbank
    Dec 23, 2010 at 1:22

5 Answers 5

23

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.

3
  • .divmod(4) returns an array. You could use .divmod(4)[1] or .modulo(4) instead ;D
    – PeterWong
    Dec 23, 2010 at 2:33
  • @PeterWong thanks for pointing that out. It's been corrected. Dec 23, 2010 at 2:34
  • Thanks! Sorry for the long delay in response, holiday! :-)
    – Chanpory
    Jan 18, 2011 at 6:53
14

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) 
1
  • 1
    This answer along with use of this article, was the best approach for me
    – Aleks
    Dec 1, 2017 at 14:20
9

I know this is an old thread but it's always nice to keep it current for future seekers.

Let's assume today is say Friday the 19th of August. All I do to get my nearest Monday is this:

monday = Date.today.monday

Then from there you can go back a week or forward a week like this:

last_monday = monday.last_week
next_monday = monday.next_week
0
6

Assuming you want both directions: Date.today.beginning_of_week + 7*(Date.today.wday/5)

1

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 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.