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
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.
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.
=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.
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]
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