7.11. Finding the Week of the Year
The definition of "week number" is not absolute and fixed. Various businesses, coalitions, government agencies, and standards bodies have differing concepts of what it means. This stems, of course, from the fact that the year can start on any day of the week; we may or may not want to count partial weeks, and we may start on Sunday or Monday.
We offer only three alternatives in this section. The first two are made available by the Time method strftime. The %U specifier numbers the weeks starting from Sunday, and the %W specifier starts with Monday.
The third possibility comes from the Date class. It has an accessor called cweek, which returns the week number based on the ISO 8601 definition (which says that week 1 is the week containing the first Thursday of the year).
If none of these three suits you, you may have to "roll your own." We present these three in a single code fragment:
require "date" # Let's look at May 1 in the years # 2002 and 2005. t1 = Time.local(2002,5,1) d1 = Date.new(2002,5,1) week1a = t1.strftime("%U").to_i # 17 week1b = t1.strftime("%W").to_i # 17 week1c = d1.cweek # 18 t2 = Time.local(2005,5,1) d2 = Date.new(2005,5,1) week2a = t2.strftime("%U").to_i # 18 week2b = t2.strftime("%W").to_i # 18 week2c = d2.cweek # 17