Posted By

gdonald on 09/27/06


Tagged

nth weekday


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

webstic


Rails nth weekday


 / Published in: Ruby
 

  1. require "date"
  2. require "date2"
  3.  
  4. class DateCalc
  5.  
  6. ######################################################
  7. # Returns the date for a specified day on a numbered
  8. # week as a date object. Such as finding the 3rd Wed
  9. # in March, 2006.
  10. #
  11. # example: nth_weekday(2005,1,2,0)
  12. # (2nd Sunday in January 2005) -> Jan 8th, 2005
  13. #
  14. # Returns: Date object
  15. ######################################################
  16. def nth_weekday(year,month,week,day)
  17. test_date = Date.new(year,month,1)
  18. last_day = Date.new(test_date.year, test_date.month, -1).day
  19. first_weekday = test_date.wday
  20. offset = first_weekday - (day % 7)
  21. weeks = (last_day) / 7
  22. test_date + (week * 7) - offset
  23. end
  24.  
  25. end

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: thopre on February 27, 2011

I have written the gem 'weekday' which does such calculations. You can call it with this syntax:

myday = Weekday.second_sunday(2005,1)

You need to login to post a comment.