Rails Previous Sunday in Relation to Any DateTime

Rails has a convenience method for calculating the beginning of the week.

irb(main):001:0> Date.today.beginning_of_week(:sunday)
#=> Sun, 16 Dec 2012

See the Date Rails extensions for other possibilities: http://api.rubyonrails.org/classes/Date.html

Update: Rails 5.2 adds convenience methods to find the next/previous occurrence of a day.

[1] pry(main)> Date.today.prev_occurring(:sunday)
#=> Sun, 29 Apr 2018

See the DateAndTime::Calculations documentation for prev_occurring and next_occurring.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)