ruby-on-railsrubyruby-on-rails-3ruby-on-rails-3.2

Rails how to create an array of months based on a range of dates


Example I have:

  range = start.to_date..(end.to_date + 1.day)

end and start are dates.

How do I create a month array based on this range?

Example:

I have the dates 23/1/2012 and 15/3/2012

The months are Januar, Februar and Marts.

I want to get a array like ["1/1/2012", "1/2/2012", "1/3/2012"]

and if the range was betweeen 25/6/2012 to the 10/10/2012

the array would be: ["1/6/2012", "1/7/2012", "1/8/2012", "1/9/2012", "1/10/2012"]


Solution

  • require 'date'
    
    date_from  = Date.parse('2011-10-14')
    date_to    = Date.parse('2012-04-30')
    date_range = date_from..date_to
    
    date_months = date_range.map {|d| Date.new(d.year, d.month, 1) }.uniq
    date_months.map {|d| d.strftime "%d/%m/%Y" }
    # => ["01/10/2011", "01/11/2011", "01/12/2011", "01/01/2012",
    #     "01/02/2012", "01/03/2012", "01/04/2012"]