Is it possible to create a list of months between two dates in Rails

后端 未结 4 439
情书的邮戳
情书的邮戳 2020-12-31 13:38

I am trying to create a page to display a list of links for each month, grouped into years. The months need to be between two dates, Today, and The date of the first entry.<

4条回答
  •  傲寒
    傲寒 (楼主)
    2020-12-31 14:09

    I don't know if I've completely understood your problem, but some of the following might be useful. I've taken advantage of the extensions to Date provided in ActiveSupport:

    d1 = Date.parse("20070617") # => Sun, 17 Jun 2007
    d2 = Date.parse("20090529") #=> Fri, 29 May 2009
    eom = d1.end_of_month #=> Sat, 30 Jun 2007
    mth_ends = [eom] #=> [Sat, 30 Jun 2007]
    while eom < d2
      eom = eom.advance(:days => 1).end_of_month
      mth_ends << eom
    end
    yrs = mth_ends.group_by{|me| me.year}
    

    The final line uses another handy extension: Array#group_by, which does pretty much exactly what it promises.

    d1.year.upto(d2.year) do |yr|
      puts "#{yrs[yr].min}, #{yrs[yr].max}"
    end
    2007-06-30, 2007-12-31
    2008-01-31, 2008-12-31
    2009-01-31, 2009-05-31
    

    I don't know if the start/end points are as desired, but you should be able to figure out what else you might need.

    HTH

提交回复
热议问题