Working with a Rails 3 application. Given a DateTime, I need to produce the Datetime for the previous Sunday. If the DateTime is a Sunday, then I want that Sunday itself back. Here's some examples:
November 7, 2011 => November 6, 2011 November 6, 2011 => November 6, 2011 November 5, 2011 => October 30, 2011
Any ideas? I'm a bit stuck.
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
.
class DateTime
def previous_sunday
self - wday
end
end
…but this is so easy, there's no reason to monkey patch it into the class :)
irb(main):001:0> require 'date'; now = DateTime.now
#=> #<DateTime: 2011-11-10T21:10:04-07:00 (…)>
irb(main):002:0> sunday = now - now.wday
#=> #<DateTime: 2011-11-06T21:10:04-07:00 (…)>
The wday
(weekday) will be 0
for any Sunday, and so no change to the date will take place.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With