Ruby 中有没有办法计算给定年份的周数(ISO 8601)?我目前正在使用查找表,我想停止使用它。
问问题
3582 次
3 回答
13
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}
产生与维基百科相同的列表
于 2011-10-31T11:30:21.907 回答
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
于 2011-10-31T11:00:22.237 回答
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
于 2011-10-31T10:24:23.080 回答