LoginSignup
2
2

More than 5 years have passed since last update.

Rails で指定日から前月までの月の一覧を生成する

Posted at

特定の日付から前月までの月の一覧を取得したかった時に、
簡単なやり方ないかなーと調べた時のメモ

当初の思いついたやり方

target_months = ('2014-02-10'.to_date..Time.zone.now.to_date.prev_month.end_of_month).map { |date| date.strftime("%Y%m") }.uniq

このやり方だと、起算日から経過日数分ループがまわるのがなんか気に入らなかったので、
下記のやり方に修正した。
記述は増えたけど、ループの数は、月数分だけになった。

修正後のやり方

# 変数名はテキトーです。
target_months = []
start_date = '2014-02-10'.to_date
end_date = Time.zone.now.to_date.prev_month.end_of_month

diff_month_count = ( end_date.year * 12 + end_date.month ) - ( start_date.year * 12 + start_date.month ) + 1
diff_month_count.times {|n| target_months << end_date.months_ago(n).strftime('%Y%m') }

月の差分を計算して、その分 target_months に突っ込むように変えました。
月の差分でプラス1したのは、timesn が 0 から始まるので、追加してます。

う〜ん。どっちにしてもスマートじゃない…

2
2
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2