Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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"]

like image 733
Rails beginner Avatar asked Sep 22 '12 13:09

Rails beginner


Video Answer


1 Answers

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"]  
like image 109
Lars Haugseth Avatar answered Oct 13 '22 20:10

Lars Haugseth