Ruby: Number of weekdays between dates

Posted by Matt on August 27, 2008

Here is a simple monkeypatch (duckpunch, donkeykick, squirrelbite, etc) to the Date class that easily allows us to calculate the number of weekdays between two dates. I can't believe that this functionality doesn't exist in the standard lib, but I'm normally the last person to mess with Date/Time calculations because they are absolute evil.

Drop this sucker into a file named "date.rb" in your Rails app's config/lib directory and restart.

Usage: Date.today.weekdays_until(some_date_in_the_future)


class Date
  def weekdays_until(date)
    return 0 if date <= self
    (self..date).select{|day| day.is_weekday?}.size
  end

  def is_weekday?
    self.wday != 0 && self.wday != 6
  end

end