0

I want to return an array of dates, between two dates, either by weekly, bi-weekly or monthly. To keep it simply, I'll focus on weekly and monthly.


today = Date.today

# Not what I want but this shows all the days for the range:
(today.beginning_of_year..today.end_of_year).map { |date| date }

# Weekly
# I'm not comfortable hardcoding "7" but it MAY work.
# The same for by-weekly: 14
(today.beginning_of_year..today.end_of_year).step(7).map { |date| date }

I could get away with the above but let's look at monthly.

[..]

(today.beginning_of_year..today.end_of_year).step(31).map { |date| date }

I've hardcoded 31. Not all months has 31 days. How to cater for months with less than 31 days? What's the best way to approach this. The aim is to return an array of dates, based on an interval (weekly, monthly etc) within a date range.

Has this been answered? Where? Thanks.

Sylar
  • 11,422
  • 25
  • 93
  • 166
  • Is the starting range always the beginning of the year? What dates are expected if it's not? What is expected of February if the date is 30.01 for example? – Siim Liiser Sep 02 '22 at 06:37
  • Yes. Siim's link is what I'm after. You may close this post. Many thanks. – Sylar Sep 02 '22 at 06:41
  • 2
    `beginning_of_year` – seems like you're using Rails. You also have [`Date#advance`](https://api.rubyonrails.org/classes/Date.html#method-i-advance) then which allows you to increment a date by days, weeks, months, and years. – Stefan Sep 02 '22 at 06:45

0 Answers0