How can I get the past x months from a giving date?
so for instance, if the date is 2023-01-04, and I want the past 3 months (including the current date), it would give me an array
of:
[
'2023-01-01',
'2022-12-01',
'2022-11-01'
]
I tried with:
current_month = Date.today.month
3.downto(1).map { |n| Date.parse(DateTime::MONTHNAMES.drop(1)[(current_month - n) % 12]).strftime('%Y-%m-%d') }
It worked fine when the year wasn't over and it only gives the months for that giving year and for the new year, it outputs completely wrong dates.
PS: I have seen a few solutions but nothing works
CodePudding user response:
You can use methods like beginning_of_month
and Rails handles simple date math quite easily:
edit: using the OP's original form:
2.downto(0).map {|i| Date.today.beginning_of_month - (i).months}
As tadman points out this is cleaner. They would just have to make the logical shift of "I want three months" = 3 - 1 down to 0 somewhere else in code.
my_dates = (1..3).map {|i| Date.today.beginning_of_month - (i - 1).months}
#=> [Sun, 01 Jan 2023, Thu, 01 Dec 2022, Tue, 01 Nov 2022]
That output looks weird because the console is showing date objects, so they should be a different color than the square brackets and the comma between the dates.