使用Ruby计算一年中的周数

时间:2011-10-31 09:44:57

标签: ruby date week-number

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

3 个答案:

答案 0 :(得分:11)

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} 

产生与wikipedia

相同的列表

答案 1 :(得分: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

答案 2 :(得分:0)

您可以执行以下操作:

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