Skip to content

Instantly share code, notes, and snippets.

@ottbot
Created October 28, 2009 17:03
Show Gist options
  • Save ottbot/220618 to your computer and use it in GitHub Desktop.
Save ottbot/220618 to your computer and use it in GitHub Desktop.
month = 5
year = 2009
century = (year - (year % 100))/100
century_offset = ((39 - century) % 4) * 2
is_leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
year_offset = ((year % 100) + (year % 100)/4) % 7
year_offset -= 1 if is_leap && [1,2].include?(month)
month_data = {1 => {:offset => 0, :days => 31},
2 => {:offset => 3, :days => 28},
3 => {:offset => 3, :days => 31},
4 => {:offset => 6, :days => 30},
5 => {:offset => 1, :days => 31},
6 => {:offset => 4, :days => 30},
7 => {:offset => 6, :days => 31},
8 => {:offset => 2, :days => 31},
9 => {:offset => 5, :days => 30},
10 => {:offset => 0, :days => 31},
11 => {:offset => 3, :days => 30},
12 => {:offset => 5, :days => 31}}
days = {0 => "Sun",
1 => "Mon",
2 => "Tues",
3 => "Wed",
4 => "Thr",
5 => "Fri",
6 => "Sat"}
# to find just the weekday, do this:
# day = 20 #calender day
# weekday_number = (century_offset + year_offset + month_data[month][:offset] + (day % 7)) % 7
# weekday = days[weekday_number]
offsets = century_offset + year_offset + month_data[month][:offset]
saturday_modulo = 6 - (offsets)
num_days = month_data[month][:days]
num_days += 1 if (is_leap && month == 2)
sats = []
suns = []
(1..num_days).each do |d|
sats << d if d % 7 == saturday_modulo % 7
suns << d if d % 7 == - offsets % 7
end
puts "Saturdays " + sats.join(', ')
puts "Sundays " + suns.join(', ')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment