Calculating the number of weeks in a year with Ruby

后端 未结 3 1710
抹茶落季
抹茶落季 2020-12-03 18:31

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.

3条回答
  •  温柔的废话
    2020-12-03 19:15

    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
    

提交回复
热议问题