Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Ruby – Get the past x months from a giving date

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading