Skip to content

Instantly share code, notes, and snippets.

@garethrees
Last active October 9, 2017 09:31
Show Gist options
  • Select an option

  • Save garethrees/5c584fe778fc789ab1e83fecff27ba0e to your computer and use it in GitHub Desktop.

Select an option

Save garethrees/5c584fe778fc789ab1e83fecff27ba0e to your computer and use it in GitHub Desktop.
Collect start and end of month for given time range in Ruby (Rails)
def start_and_end_of_month(date)
[date.beginning_of_month,
date.end_of_month]
end
def collect_dates(start_date, end_date = Time.zone.now.last_month.end_of_month, memo = [])
if start_date < end_date
memo << start_and_end_of_month(start_date)
collect_dates(start_date.next_month, end_date, memo)
else
memo
end
end
start_date = Time.zone.now.beginning_of_year
end_date = Time.zone.now.last_month.end_of_month
dates = collect_dates(start_date, end_date)
# => [[Sun, 01 Jan 2017 00:00:00 GMT +00:00, Tue, 31 Jan 2017 23:59:59 GMT +00:00],
# [Wed, 01 Feb 2017 00:00:00 GMT +00:00, Tue, 28 Feb 2017 23:59:59 GMT +00:00],
# [Wed, 01 Mar 2017 00:00:00 GMT +00:00, Fri, 31 Mar 2017 23:59:59 BST +01:00],
# [Sat, 01 Apr 2017 00:00:00 BST +01:00, Sun, 30 Apr 2017 23:59:59 BST +01:00],
# [Mon, 01 May 2017 00:00:00 BST +01:00, Wed, 31 May 2017 23:59:59 BST +01:00],
# [Thu, 01 Jun 2017 00:00:00 BST +01:00, Fri, 30 Jun 2017 23:59:59 BST +01:00],
# [Sat, 01 Jul 2017 00:00:00 BST +01:00, Mon, 31 Jul 2017 23:59:59 BST +01:00],
# [Tue, 01 Aug 2017 00:00:00 BST +01:00, Thu, 31 Aug 2017 23:59:59 BST +01:00],
# [Fri, 01 Sep 2017 00:00:00 BST +01:00, Sat, 30 Sep 2017 23:59:59 BST +01:00]]
dates.map do |start_date, end_date|
[start_date.strftime('%Y-%m-%d'),
end_date.strftime('%Y-%m-%d')]
end
# => [["2017-01-01", "2017-01-31"],
# ["2017-02-01", "2017-02-28"],
# ["2017-03-01", "2017-03-31"],
# ["2017-04-01", "2017-04-30"],
# ["2017-05-01", "2017-05-31"],
# ["2017-06-01", "2017-06-30"],
# ["2017-07-01", "2017-07-31"],
# ["2017-08-01", "2017-08-31"],
# ["2017-09-01", "2017-09-30"]]
@garethrees
Copy link
Copy Markdown
Author

str = dates.map do |start_date, end_date|
  [start_date.strftime('%Y-%m-%d'),
   end_date.strftime('%Y-%m-%d')].join(' ')
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment