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).
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"]
For week use step.
(Date.parse("2014-01-30")..Date.parse("2014-03-27")).step(7).map(&:to_s)
For month it will not work, because number of days varies.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With