Method: RiCal::FastDateTime#nth_wday_in_month

Defined in:
lib/ri_cal/fast_date_time.rb

#nth_wday_in_month(n, which_wday) ⇒ Object

e.g. to obtain the 3nd Tuesday of the receivers month use

time.nth_wday_in_month(2, 2)


162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/ri_cal/fast_date_time.rb', line 162

def nth_wday_in_month(n, which_wday)
  first_of_month = change(:day => 1)
  first_in_month = first_of_month.advance(:days => (which_wday - first_of_month.wday))
  first_in_month = first_in_month.advance(:days => 7) if first_in_month.month != first_of_month.month
  if n > 0
    first_in_month.advance(:days => (7*(n - 1)))
  else
    possible = first_in_month.advance(:days => 21)
    possible = possible.advance(:days => 7) while possible.month == first_in_month.month
    last_in_month = possible.advance(:days => - 7)
    (last_in_month.advance(:days => - (7*(n.abs - 1))))
  end
end