Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

210
Views
Get the first Monday of every quarter in Rails

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.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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
over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!