Calculating the number of weeks in a year with Ruby

爱⌒轻易说出口 提交于 2019-11-28 12:17:37
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

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!