Get the first Monday of every quarter in Rails

Viewed 175

What is the cleanest way to get the first Monday of every quarter of the year in Ruby on Rails?

The solutions i found looks terrible to me: Check if today is one of the first 7 days of the month, then check if today is Monday and finally look if this month is included in one of the 4 months of the quarter.

I think it should be a better way to accomplish this.

2 Answers

Here's my approach:

first_day = Date.today.beginning_of_year
mondays = 4.times.map do |i|
  first_day_of_quarter = first_day.advance(months: 3 * i).beginning_of_quarter
  first_day_of_quarter.monday? ? first_day_of_quarter : first_day_of_quarter.next_week
end

# [0] Mon, 04 Jan 2021,
# [1] Mon, 05 Apr 2021,
# [2] Mon, 05 Jul 2021,
# [3] Mon, 04 Oct 2021

Here is a pure-Ruby solution.

def first_monday_by_quarter(year)
  [1, 4, 7, 10].map do |month|
    d = Date.new(year, month, 1)
    d.wday.zero? ? (d+1) : d+8-d.wday
  end
end
first_monday_by_quarter(2022)
  #=> [#<Date: 2022-01-03 ((2459583j,0s,0n),+0s,2299161j)>,
  #    #<Date: 2022-04-04 ((2459674j,0s,0n),+0s,2299161j)>,
  #    #<Date: 2022-07-04 ((2459765j,0s,0n),+0s,2299161j)>,
  #    #<Date: 2022-10-03 ((2459856j,0s,0n),+0s,2299161j)>]
first_monday_by_quarter(Date.today.year)
  #=> #<Date: 2021-01-04 ((2459219j,0s,0n),+0s,2299161j)>,
  #   #<Date: 2021-04-05 ((2459310j,0s,0n),+0s,2299161j)>,
  #   #<Date: 2021-07-05 ((2459401j,0s,0n),+0s,2299161j)>,
  #   #<Date: 2021-10-04 ((2459492j,0s,0n),+0s,2299161j)>]

If desired, one could shorten Date.new(year, month, 1) to Date.new(year, month). require 'date' would be needed if this were used in pure-Ruby code.

Related