How to find the end date of a week in Ruby?

I have the following date object in Ruby

Date.new(2009, 11, 19) 

How will I find next Friday?

+4
source share
5 answers

You can use end_of_week (AFAIK is only available in Rails)

 >> Date.new(2009, 11, 19).end_of_week - 2 => Fri, 20 Nov 2009 

But that may not work, depending on what exactly you want. Another way -

 >> d = Date.new(2009, 11, 19) >> (d..(d+7)).find{|d| d.cwday == 5} => Fri, 20 Nov 2009 

suggests that you want to have the following Friday, if d is already on Friday:

 >> d = Date.new(2009, 11, 20) # was friday >> ((d+1)..(d+7)).find{|d| d.cwday == 5} => Fri, 27 Nov 2009 
+13
source

 d = Date.new(2009, 11, 19) d+=(5-d.wday) > 0 ? 5 - d.wday : 7 + 5 - d.wday 
+2
source

An old question, but if you use rails, you can do the following to get on next Friday.

 Date.today.sunday + 5.days 

Similarly, you can do the following to get this Friday.

 Date.today.monday + 4.days 
+2
source

Rails ActiveSupport :: CoreExtensions :: Date :: Calculations contains methods that can help you. If you are not using Rails, you can simply require ActiveSupport.

+1
source

Since the Ruby modulo (%) operation returns positive numbers when your divisor is positive, you can do this:

 some_date = Date.new(2009, 11, 19) next_friday = some_date + (5 - some_date.cwday) % 7 

The only problem I see here is that if some_date is Friday, next_friday will be the same date as some_date . If this is not the desired behavior, a small modification may be used instead:

 some_date = Date.new(...) day_increment = (5 - some_date.cwday) % 7 day_increment = 7 if day_increment == 0 next_friday = some_date + day_increment 

This code does not depend on additional external dependencies and mainly depends on integer arithmetic.

+1
source

All Articles