2
def monday?
  require 'chronic'
  today = Date.today
  1st_monday = Chronic.parse('1st monday of this month', now: today.beginning_of_month).to_date
  3rd_monday = Chronic.parse('3th monday of this month', now: today.beginning_of_month).to_date
  return today == 1st_monday || today == 3rd_monday
end

I have defined this method to select the first or third monday of each month. The issue arose today as Chronic selected June 8th as the first monday of the month which is wrong as June 1st was the first monday. Any idea how this issue can be resolved? Could it be because we have five mondays this month which confused Chronic?

anothermh
  • 9,815
  • 3
  • 33
  • 52
user12763413
  • 1,177
  • 3
  • 18
  • 53
  • 1
    Interestingly `Chronic.parse('1st monday of this June')` works fine. Maybe try something like `Chronic.parse("1st monday of this #{today.strftime('%B')}")`, but that shouldn't really be needed. – Eli Sadoff Jun 08 '20 at 17:05
  • 2
    looks like existing bug on Chronic that was never solved: https://github.com/mojombo/chronic/issues/295 – Olkin Jun 08 '20 at 17:20
  • This is about Rails, not Ruby. – anothermh Jun 08 '20 at 17:33

1 Answers1

-1

Seems to be a bug in the Chronic gem. Guess you'll have to go with this solution:

month = Date.today.strftime('%B')
=>"June"

Chronic.parse("3st monday of this #{month}")

=> 2020-06-15 12:00:00 -0400
lacostenycoder
  • 10,623
  • 4
  • 31
  • 48
  • I have this method run everyday using a sidekiq and this method checks whether its the first monday or third – user12763413 Jun 08 '20 at 17:36
  • see updated answer, if past can't parse, it returns nil, so you can fallback to future. – lacostenycoder Jun 08 '20 at 17:43
  • Chronic.parse('3rd monday of this month', context: :past) || Chronic.parse('3rd monday of this month') I tried this, and it returned June 29th which is the 5th monday of the month. – user12763413 Jun 08 '20 at 17:45