Techioz Blog

Railsで日付の範囲に基づいて月の配列を作成する方法

概要

私が持っている例:

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

終了と開始は日付です。

この範囲に基づいて月の配列を作成するにはどうすればよいですか?

例:

日付は 2012/1/23 と 2012/3/15 です。

月は1月、2月、火星です。

[“1/1/2012”, “1/2/2012”, “1/3/2012”] のような配列を取得したい

範囲が 2012 年 6 月 25 日から 2012 年 10 月 10 日までの間の場合

配列は次のようになります: [“1/6/2012”, “1/7/2012”, “1/8/2012”, “1/9/2012”, “1/10/2012”]

解決策

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