2

在 Ruby on Rails 中获得每个季度的第一个星期一的最干净的方法是什么?

我发现的解决方案对我来说看起来很糟糕:检查今天是否是该月的前 7 天之一,然后检查今天是否是星期一,最后查看本月是否包含在本季度的 4 个月之一中。

我认为这应该是实现这一目标的更好方法。

4

2 回答 2

3

这是一个纯 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). require 'date'如果在纯 Ruby 代码中使用它,则需要它。

于 2021-12-09T20:09:32.687 回答
3

这是我的方法:

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
于 2021-12-09T11:21:41.683 回答