【问题标题】:Calculating the number of weeks in a year with Ruby用 Ruby 计算一年中的周数
【发布时间】:2011-10-31 09:44:56
【问题描述】:

Ruby 中有没有一种方法可以计算给定年份的周数(ISO 8601)?我目前正在使用查找表,我想停止使用它。

【问题讨论】:

    标签: ruby date week-number


    【解决方案1】:
    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} 
    

    产生与wikipedia相同的列表

    【讨论】:

    • 我更喜欢你的其他答案,因为它使用了定义,而这个答案只是......有效:P
    • 好吧,维基百科也提到了 12 月 28 日:en.wikipedia.org/wiki/ISO_week_date#Last_week,第三点。
    • 维基百科 2,rwilliams 0。再次感谢。
    【解决方案2】:
    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
    

    【讨论】:

    • d.wday == 4 || d.leap? && d.wday == 3 ? 53 : 52 怎么样?
    • 好东西。我错过了维基百科上关于 53 周年定义的部分。
    【解决方案3】:

    您可以执行以下操作:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-23
      • 2019-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多