Handling weekdays, weekends and public holidays

(1) Check if today is a weekday. (Ruby)

(1..5).cover?(Date.today.wday)

Note: wday starts at 0, which represents Sunday.

(2) Check if today is a weekday. (Rails 5)

Date.today.on_weekday?

Note: Rails hardcoded weekday as Mon to Fri. If your weekday is different, you should not use this method.

(3) Check if today is a public holiday. Assuming public holidays are stored in model PublicHoliday with a date column "effective_date".

PublicHoliday.where(effective_date: Date.today).size > 0

(4) Check if a given date "d" is a public holiday or a weekend.

PublicHoliday.where(effective_date: d).size > 0 || d.on_weekend?

(5) Given a range of dates, get the number of days that do not fall on a weekend or a public holiday.

def working_days(range)
  public_holidays = PublicHoliday.where(effective_date: range).uniq.pluck(:effective_date)
range.select { |d| d.on_weekday? && public_holidays.none? { |ph| ph == d } }.size end



AI Summary
Chrome On-device AI 2024-07-27 10:48:37

Share Article