Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating the number of weeks in a year with Ruby

Is there a way in Ruby to calculate the number of weeks(ISO 8601) for a given year? I'm currently using a lookup table and I'd like to stop using it.

like image 565
rwilliams Avatar asked Oct 31 '11 09:10

rwilliams


People also ask

How do you calculate week number in a year?

The weeks of the year in a Gregorian calendar are numbered from week 1 to week 52 or 53, depending on several varying factors. Most years have 52 weeks, but if the year starts on a Thursday or is a leap year that starts on a Wednesday, that particular year will have 53 numbered weeks.

How to get week number from date in Ruby?

How to get the week number from a date. To get the ISO week number (1-53), use date . strftime('%-V') . date is a Date or DateTime object.

How do I count my weeks?

Divide the number of days by 7 and round down. You will get the number of full weeks. Calculate the integer remainder after dividing the number of days by 7.


1 Answers

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

like image 154
steenslag Avatar answered Sep 20 '22 17:09

steenslag