Skip to content

Instantly share code, notes, and snippets.

@ihower
Created January 13, 2009 19:08
Show Gist options
  • Save ihower/46568 to your computer and use it in GitHub Desktop.
Save ihower/46568 to your computer and use it in GitHub Desktop.
nth week
def nthweek( time )
time.strftime("%U").to_i
end
def get_time_by_nthweek(i, year = Time.now.year)
first_day = Time.mktime(year,1,1)
first_day - first_day.wday.days + i*7.days
end
def next_nthweek(i, year = Time.now.year)
time = get_time_by_nthweek(i, year) + 7.days
return time.year, nthweek( time )
end
def previous_nthweek(i, year = Time.now.year)
time = get_time_by_nthweek(i, year) - 7.days
return time.year, nthweek( time )
end
# example
foo = nthweek( Time.parse('2009-01-01') ) # 0
bar = get_time_by_nthweek(foo) # 2008-12-28
foo = nthweek( Time.parse('2009-01-14') ) # 2
bar = get_time_by_nthweek(foo) # 2009-1-11
year, nthweek = next_nthweek(52, 2008) # 2009, 1
year, nthweek = previous_nthweek(1, 2009) # 2008, 52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment