Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert date range to array of weeks and months

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).

like image 297
Shpigford Avatar asked Mar 27 '14 18:03

Shpigford


2 Answers

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"]
like image 95
Arup Rakshit Avatar answered Oct 24 '22 09:10

Arup Rakshit


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.

like image 24
ciemborowicz Avatar answered Oct 24 '22 08:10

ciemborowicz