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.
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 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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With