Convert date range to array of weeks and months

date, ruby, ruby-on-rails

Solution

I can think of as below :

require 'date'

months = (Date.parse("2014-01-30")..Date.parse("2014-03-27")).group_by(&:month).map { |_,v| v.first.end_of_month.to_s } 
# => ["2014-01-31", "2014-02-28", "2014-03-31"]

weeks = (Date.parse("2014-01-30")..Date.parse("2014-03-27")).select(&:sunday?).map(&:to_s) 
# => ["2014-02-02",
#     "2014-02-09",
#     "2014-02-16",
#     "2014-02-23",
#     "2014-03-02",
#     "2014-03-09",
#     "2014-03-16",
#     "2014-03-23"]

Problem

I want to take a given date range and convert it to an array of dates that are the end of calendar weeks and months. So, same range, but would have a `weeks` and `months` output. Range: `Date.parse("2014-01-30")..Date.parse("2014-03-27")` Output: ``` weeks = ["2014-02-02", "2014-02-09", "2014-02-16", "2014-02-23", "2014-03-02", "2014-03-09", "2014-03-16", "2014-03-23", "2014-03-02", "2014-03-30"] months = ["2014-01-31", "2014-02-28", "2014-03-31"] ``` I happen to be doing this inside a Rails app, so the Rails helper methods are available here (for example, end_of_week).

Original source