Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Previous Sunday in Relation to Any DateTime

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.

like image 357
Mike Avatar asked Nov 11 '11 03:11

Mike


2 Answers

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.

like image 84
Charles Maresh Avatar answered Oct 18 '22 18:10

Charles Maresh


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.

like image 23
Phrogz Avatar answered Oct 18 '22 20:10

Phrogz