这是一个纯 Ruby 解决方案。
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)>]
如果需要,可以将Date.new(year, month, 1) 缩短为Date.new(year, month)。如果在纯 Ruby 代码中使用 require 'date',则需要它。