Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get most recently occurring Wednesday?

How would I get the most recently occurring Wednesday, using Ruby (and Rails, if there's a pertinent helper method)?

Ultimately need the actual date (5/1/2013).

like image 605
Shpigford Avatar asked May 06 '13 20:05

Shpigford


2 Answers

time = Time.now
days_to_go_back = (time.wday + 4) % 7
last_wed = days_to_go_back.days.ago
like image 73
Gray Kemmey Avatar answered Oct 09 '22 08:10

Gray Kemmey


This works in Ruby:

require 'date'

def last_wednesday(date)
  date - (date.wday - 3) % 7
end

last_wednesday(Date.today)
# => #<Date: 2013-05-01 ((2456414j,0s,0n),+0s,2299161j)>

In Rails there's beginning_of_week:

Date.today.beginning_of_week(:wednesday)
# => Wed, 01 May 2013
like image 41
Stefan Avatar answered Oct 09 '22 09:10

Stefan