Created
January 13, 2009 19:08
-
-
Save ihower/46568 to your computer and use it in GitHub Desktop.
nth week
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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