Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 761
Chanpory Avatar asked Dec 23 '10 00:12

Chanpory


1 Answers

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.

like image 182
sgriffinusa Avatar answered Oct 05 '22 22:10

sgriffinusa