Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate month end dates for last 12 months

I need a method that generates an array containing the month end date for each of the past 12 months. I've come up with the solution below. It works, however, there's probably a more elegant way to solve this problem. Any suggestions? Is there a more efficient way to generate this array? Any advice would be greatly appreciated.

require 'active_support/time'

...

def months
  last_month_end = (Date.today - 1.month).end_of_month
  months = [last_month_end]
  11.times do
    month_end = (last_month_end - 1.month).end_of_month
    months << month_end
  end
  months
end
like image 888
Ben Downey Avatar asked Jul 21 '13 14:07

Ben Downey


People also ask

How do I get Excel to automatically add months?

You can use the EDATE function to quickly add or subtract months from a date. The EDATE function requires two arguments: the start date and the number of months that you want to add or subtract. To subtract months, enter a negative number as the second argument. For example, =EDATE("9/15/19",-5) returns 4/15/19.

How do I get start and end date month data from a specific date in python?

You can use current_date. replace(day=1) to get first day in current month. And if you substract datetime. timedelta(days=1) then you get last day in previous month.

How do I get the end of the month in Excel?

=EOMONTH(A2, 1) - returns the last day of the month, one month after the date in cell A2. =EOMONTH(A2, -1) - returns the last day of the month, one month before the date in cell A2. Instead of a cell reference, you can hardcode a date in your EOMONTH formula.


1 Answers

Usually when you want an array of things start thinking about map. While you're at it why not generalize such a method so you can get back any n months you wish:

def last_end_dates(count = 12)
  count.times.map { |i| (Date.today - (i+1).month).end_of_month }
end

>> pp last_end_dates(5)

[Sun, 30 Jun 2013,
 Fri, 31 May 2013,
 Tue, 30 Apr 2013,
 Sun, 31 Mar 2013,
 Thu, 28 Feb 2013]
like image 124
Casper Avatar answered Oct 26 '22 19:10

Casper