Return to Snippet

Revision: 1344
at September 27, 2006 13:12 by gdonald


Updated Code
require "date"
require "date2"

class DateCalc

  ######################################################
  # Returns the date for a specified day on a numbered
  # week as a date object. Such as finding the 3rd Wed 
  # in March, 2006.
  # 
  #   example: nth_weekday(2005,1,2,0)
  #   (2nd Sunday in January 2005) -> Jan 8th, 2005
  #
  # Returns: Date object  
  ######################################################
  def nth_weekday(year,month,week,day)
    test_date = Date.new(year,month,1)
    last_day = Date.new(test_date.year, test_date.month, -1).day
    first_weekday = test_date.wday
    offset = first_weekday - (day % 7)
    weeks = (last_day) / 7
    test_date + (week * 7) - offset
  end
  
end

Revision: 1343
at September 27, 2006 13:12 by gdonald


Initial Code
require "date"
require "date2"

class DateCalc

  ######################################################
  # Returns the date for a specified day on a numbered
  # week as a date object. Such as finding the 3rd Wed 
  # in March, 2006.
  # 
  #   example: nth_weekday(2005,1,2,0)
  #   (2nd Sunday in January 2005) -> Jan 8th, 2005
  #
  # Returns: Date object  
  ######################################################
  def nth_weekday(year,month,week,day)
    test_date = Date.new(year,month,1)
    last_day = Date.new(test_date.year, test_date.month, -1).day
    first_weekday = test_date.wday
    offset = first_weekday - (day % 7)
    weeks = (last_day) / 7
    test_date + (week * 7) - offset
  end
  
end

Initial URL

                                

Initial Description

                                

Initial Title
Rails nth weekday

Initial Tags

                                

Initial Language
Ruby