Rails nth weekday


/ Published in: Ruby
Save to your folder(s)



Copy this code and paste it in your HTML
  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

You need to login to post a comment.