在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}
生成与wikipedia相同的列表
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