使用Ruby计算一年中的周数

Ruby中有没有办法计算给定年份的周数(ISO 8601)? 我目前正在使用查找表,我想停止使用它。

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} 

产生与维基百科相同的列表

 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 

您可以执行以下操作:

 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 

如果这就是你要找的东西:)

PS:虽然只适用于商业年份,所以在2001年,12月31日实际上是商业周刊1