在 Ruby on Rails 中獲得一年中每個季度的第一個星期一的最干凈的方法是什么?
我發現的解決方案對我來說看起來很糟糕:檢查今天是否是本月的前 7 天之一,然后檢查今天是否是星期一,最后查看本月是否包含在本季度的 4 個月之一中。
我認為這應該是實作這一目標的更好方法。
uj5u.com熱心網友回復:
這是我的方法:
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
uj5u.com熱心網友回復:
這是一個純 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 代碼中使用它,則需要。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/383482.html
