Skip to content

Instantly share code, notes, and snippets.

@yrgoldteeth
Created September 4, 2009 14:59
Show Gist options
  • Save yrgoldteeth/180931 to your computer and use it in GitHub Desktop.
Save yrgoldteeth/180931 to your computer and use it in GitHub Desktop.
# Nicholas Fine
# nicholas.fine@gmail.com
# This is just my general collection of useful methods, algorithms, etc.
##############################################################################
# Get the date for the nth weekday of a given month and year. Call date_for_nth_weekday({2009,3,:monday,3}) to
# get the third monday of april in 2009
def date_for_nth_weekday(h={:year, :month, :week_day, :nth})
days_of_week = {:sunday => 0, :monday => 1, :tuesday => 2, :wednesday => 3, :thursday => 4, :friday => 5, :saturday => 6}
twd = days_of_week[h[:week_day]]
nth_wday_of_the_month(h[:year], h[:month], twd, h[:nth])
end
def nth_wday_of_the_month(year, month, twd, n)
day_check = Date.new(year, month, 1)
while day_check.wday != twd
day_check += 1.day
end
(n - 1).times do
day_check += 7.days
end
return day_check
end
################################################################################################
# Get the date for Easter sunday given a year.
# Found easter algorithm at http://snippets.dzone.com/posts/show/7109 under a Creative Commons 3.0 license
def easter(some_year)
golden_number = (some_year % 19) + 1
if some_year <= 1752 then
# Julian calendar
dominical_number = (some_year + (some_year / 4) + 5) % 7
paschal_full_moon = (3 - (11 * golden_number) - 7) % 30
else
# Gregorian calendar
dominical_number = (some_year + (some_year / 4) - (some_year / 100) + (some_year / 400)) % 7
solar_correction = (some_year - 1600) / 100 - (some_year - 1600) / 400
lunar_correction = (((some_year - 1400) / 100) * 8) / 25
paschal_full_moon = (3 - 11 * golden_number + solar_correction - lunar_correction) % 30
end
dominical_number += 7 until dominical_number > 0
paschal_full_moon += 30 until paschal_full_moon > 0
paschal_full_moon -= 1 if paschal_full_moon == 29 or (paschal_full_moon == 28 and golden_number > 11)
difference = (4 - paschal_full_moon - dominical_number) % 7
difference += 7 if difference < 0
day_easter = paschal_full_moon + difference + 1
if day_easter < 11 then
# Easter occurs in March.
return Date.new(y=some_year, m=3, d=day_easter + 21)
else
#Easter occurs in April.
return Date.new(y=some_year, m=4, d=day_easter - 10)
end
end
################################################################
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment