Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given a date, how to find if it's the second or fourth Saturday of the month

In my Rails application, I need to find if a given date is the second or fourth Saturday of the month. What's the efficient way to do this? Is there a gem I can use?

like image 468
user1575148 Avatar asked Jan 25 '26 16:01

user1575148


2 Answers

  • Days 1 to 7 are week 0
  • Days 8 to 14 are week 1
  • Days 15 to 21 are week 2
  • Days 22 to 28 are week 3

To get the week id, we can calculate (date.day-1)/7. Since the id is zero-based, the second and fourth saturdays have an odd week id :

def second_or_fourth_saturday?(date)
  date.saturday? && ((date.day - 1) / 7).odd?
end
like image 198
Eric Duminil Avatar answered Jan 27 '26 08:01

Eric Duminil


The second Saturday has to be in the day range 8-14, and the fourth in the day range 22-28. So I think this should work

def second_or_forth_saturday?(date)
  return false unless date.saturday?
  (8..14).include?(date.day) || (22..28).include?(date.day)
end
like image 40
11 revs, 10 users 40% Avatar answered Jan 27 '26 08:01

11 revs, 10 users 40%



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!