Is there a way in Ruby to calculate the number of weeks(ISO 8601) for a given year? I'm currently using a lookup table and I'd like to stop using it.
Asked
Active
Viewed 3,784 times
3 Answers
14
def num_weeks(year = Date.today.year)
Date.new(year, 12, 28).cweek # magick date!
end
long_iso_years = (2000..2400).select{|year| num_weeks(year) == 53}
Yields the same list as wikipedia

steenslag
- 79,051
- 16
- 138
- 171
-
I like your other answer better because it uses the definition while this answer just....works :P – rwilliams Oct 31 '11 at 13:22
-
Well, wikipedia mentions 28 december too: http://en.wikipedia.org/wiki/ISO_week_date#Last_week , third point. – steenslag Oct 31 '11 at 14:26
-
Wikipedia 2, rwilliams 0. Thanks again. – rwilliams Oct 31 '11 at 15:46
5
require 'date'
def num_weeks(year = Date.today.year)
# all years starting with Thursday, and leap years starting with Wednesday have 53 weeks
# http://en.wikipedia.org/wiki/ISO_week_date#Last_week
d = Date.new(year, 1, 1)
return 53 if d.wday == 4
return 53 if d.leap? and d.wday == 3
52
end

steenslag
- 79,051
- 16
- 138
- 171
-
1
-
Good stuff. I missed that section on the definition of the 53 week year on wikipedia. – rwilliams Oct 31 '11 at 13:10
0
You can do the following:
require 'date'
@year = 2001 #year you want to count the number of weeks
d = Date.new @year, 12, 30 # as in Date.new
d.cweek # returns the commercial week number for the last week of the year, in this case, 52
if that's what you're looking for :)
PS: that only works for commercial year though, so in 2001, the 31th of December was actually commercial week 1

Elland
- 207
- 3
- 7