2016-06-24 36 views
0

在我的應用程序中,我存儲的活動範圍爲1到31的day_numberhours。任何活動屬於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 

如何確定屬於某個特定周的日數?

回答

0

我決定使用week-of-month寶石,這給了我一個week_split方法,用了一個月的全周,每個星期所有天返回數組:Date.new(2012,1,1).week_split回報:

[[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) 
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

希望,這將幫助你。

+0

謝謝,但將錯過8和31之間 – John

+0

一天號活動通過將上述邏輯到您的「weeknrs」循環。你將在first_week到上週之間整天工作。防爆。 Date.commercial(2016,1,1)其中2016年爲年,中期1爲周,最後1爲週一。 –

+0

啊,現在我明白你的意思了,我錯過了具體的商業方法。 – John