2

我一直在寻找几个小时,我只是找不到正确的答案。
希望你能帮助我。

红宝石: 1.9.3p194
导轨: 3.2.8

目标:

1.9.3p194 :001 > get_weeknumbers_in_month 1, 2012
=> [1, 2, 3, 4]
1.9.3p194 :002 > get_weeknumbers_in_month 2, 2012
=> [5, 6, 7, 8]
1.9.3p194 :003 > get_weeknumbers_in_month 3, 2012
=> [9, 10, 11, 12, 13]
1.9.3p194 :004 > get_weeknumbers_in_month 4, 2012
=> [14, 15, 16, 17]

get_weeknumbers_in_month所以,当调用该方法时,我实际上想要一个日历周数数组。


研究:

要从日期获取月份数:

DateTime.parse("2012-01-10").month
=> 1



获取一个月的天数:

Time::days_in_month(1, 2012)
=> 31



要获取日期的日历周数:

DateTime.parse("2012-04-12").strftime("%W").to_i
=> 15



有人可以帮我解决这个问题吗?

提前致谢。

4

1 回答 1

0

如果我明白了,你就差不多完成了!最后是计算月份的第一个和最后一个日期,不是吗?所以类似 next 的东西可能会起作用(未经测试)

def get_weeknumbers_in_month(month, year)
  first_week_num = Date.new(year,month,1).strftime("%U").to_i
  last_week_num = Date.new(year,month,1).end_of_month.strftime("%U").to_i
  (first_week_num..last_week_num).to_a
end
于 2012-11-06T15:30:46.863 回答