获取一周数字的日期编号

时间:2016-06-24 11:17:51

标签: ruby-on-rails

在我的应用程序中,我存储day_number范围为1到31且数量为hours的活动。任何活动都属于timesheet,其中包含monthyear

现在,我希望概述一年中的所有星期以及该周的活动小时数。我确定了一个月的周数:

first_week = Date.new(timesheet.year,timesheet.month,1).strftime("%U").to_i
last_week = Date.new(timesheet.year,timesheet.month,1).end_of_month.strftime("%U").to_i
weeknrs = (first_week..last_week).to_a
weeknrs.each do |weeknr|
  # Do something
end

如何确定属于特定周的日期数?

2 个答案:

答案 0 :(得分:6)

请试试这个

1..7.each do |i|
 Date.commercial(timesheet.year, weeknr, i)
end

有关更多参考资料,请查看

http://ruby-doc.org/stdlib-2.3.1/libdoc/date/rdoc/Date.html#method-c-commercial

希望,这会对你有帮助。

答案 1 :(得分:0)

我决定使用week-of-month gem,它为我提供了一个week_split方法,该方法返回一个月中所有星期和所有日期每周的数组:Date.new(2012,1,1).week_split返回:< / p>

 [[1, 2, 3, 4, 5, 6, 7],
    [8, 9, 10, 11, 12, 13, 14],
    [15, 16, 17, 18, 19, 20, 21],
    [22, 23, 24, 25, 26, 27, 28],
    [29, 30, 31]]

现在我可以轻松地迭代这个数组并查询活动:

- weeks = Date.new(year,month,1).week_split
- weeks.each do |week|
  - activities = Activity.where("month = ? AND year = ? AND day IN (?)", timesheet.month, timesheet.year, week)