2015-11-02 96 views
0

我想要在下一年創建日期範圍對的連續列表,包括數週,數月和四周。在導軌中打印日期範圍

因此,例如,我需要有一個日期範圍2/11/2015 - 08/11/2015,在今年餘下時間循環。

幾個月它將需要生產2015年1月11日 - 2015年11月30日,在今年餘下時間循環。

任何幫助將不勝感激!

+0

你有什麼已經嘗試解決你自己的問題? – MarsAtomic

回答

0

使用的ActiveSupport,Rails添加方法Fixnum對象如#days,​​,#months#fortnights,和#years

https://github.com/rails/rails/blob/ef5144d8a5529baebdaf76dbf253d1d6f2d8689b/activesupport/lib/active_support/core_ext/numeric/time.rb

https://github.com/rails/rails/blob/ef5144d8a5529baebdaf76dbf253d1d6f2d8689b/activesupport/lib/active_support/core_ext/integer/time.rb

下面的例子是不完美的,因爲它沒有考慮到奇怪的日期的情況下(如具有53週年)。我相信別人會有更好的解決方案。一旦日期超過Date.today + 1.year,您也可以通過跳出循環來改善我的解決方案。我想保持簡單的演示目的。

(1..52).each_with_object([]) do |week_idx, memo| 
    memo << [Date.today + (week_idx - 1).weeks, Date.today + week_idx.weeks] 
end 
0
weeks_ary = Array.new 
month_ary = Array.new 
(Date.today..Date.today.next_year).each do |date| 
    if date.wday == 1 
     end_week = date + 6.days 
     weeks_ary << "#{date.strftime('%d/%m/%Y')} - #{end_week.strftime('%d/%m/%Y')}" 
    end 
    if date.strftime('%d') == "01" 
     month_ary << "#{date.strftime('%d/%m/%Y')} - #{date.end_of_month.strftime('%d/%m/%Y')}" 
    end 
end 
#output: 
# weeks_ary = ["02/11/2015 - 08/11/2015", "09/11/2015 - 15/11/2015", "16/11/2015 - 22/11/2015", "23/11/2015 - 29/11/2015", "30/11/2015 - 06/12/2015", "07/12/2015 - 13/12/2015", "14/12/2015 - 20/12/2015", "21/12/2015 - 27/12/2015", "28/12/2015 - 03/01/2016", "04/01/2016 - 10/01/2016", "11/01/2016 - 17/01/2016", "18/01/2016 - 24/01/2016", "25/01/2016 - 31/01/2016", "01/02/2016 - 07/02/2016", "08/02/2016 - 14/02/2016", "15/02/2016 - 21/02/2016", "22/02/2016 - 28/02/2016", "29/02/2016 - 06/03/2016", "07/03/2016 - 13/03/2016", "14/03/2016 - 20/03/2016", "21/03/2016 - 27/03/2016", "28/03/2016 - 03/04/2016", "04/04/2016 - 10/04/2016", "11/04/2016 - 17/04/2016", "18/04/2016 - 24/04/2016", "25/04/2016 - 01/05/2016", "02/05/2016 - 08/05/2016", "09/05/2016 - 15/05/2016", "16/05/2016 - 22/05/2016", "23/05/2016 - 29/05/2016", "30/05/2016 - 05/06/2016", "06/06/2016 - 12/06/2016", "13/06/2016 - 19/06/2016", "20/06/2016 - 26/06/2016", "27/06/2016 - 03/07/2016", "04/07/2016 - 10/07/2016", "11/07/2016 - 17/07/2016", "18/07/2016 - 24/07/2016", "25/07/2016 - 31/07/2016", "01/08/2016 - 07/08/2016", "08/08/2016 - 14/08/2016", "15/08/2016 - 21/08/2016", "22/08/2016 - 28/08/2016", "29/08/2016 - 04/09/2016", "05/09/2016 - 11/09/2016", "12/09/2016 - 18/09/2016", "19/09/2016 - 25/09/2016", "26/09/2016 - 02/10/2016", "03/10/2016 - 09/10/2016", "10/10/2016 - 16/10/2016", "17/10/2016 - 23/10/2016", "24/10/2016 - 30/10/2016", "31/10/2016 - 06/11/2016"] 
# month_ary = ["01/12/2015 - 31/12/2015", "01/01/2016 - 31/01/2016", "01/02/2016 - 29/02/2016", "01/03/2016 - 31/03/2016", "01/04/2016 - 30/04/2016", "01/05/2016 - 31/05/2016", "01/06/2016 - 30/06/2016", "01/07/2016 - 31/07/2016", "01/08/2016 - 31/08/2016", "01/09/2016 - 30/09/2016", "01/10/2016 - 31/10/2016", "01/11/2016 - 30/11/2016"]