Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find date of end of week in Ruby?

I have the following date object in Ruby

Date.new(2009, 11, 19)

How would I find the next Friday?

like image 876
Ben Waterman Avatar asked Nov 19 '09 16:11

Ben Waterman


1 Answers

You could use end_of_week (AFAIK only available in Rails)

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

But this might not work, depending what exactly you want. Another way could be to

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

lets assume you want to have the next friday if d is already a friday:

>> d = Date.new(2009, 11, 20) # was friday
>> ((d+1)..(d+7)).find{|d| d.cwday == 5}
=> Fri, 27 Nov 2009
like image 103
reto Avatar answered Oct 06 '22 00:10

reto