In Ruby 2.1.1, the Date class has a friday?
method
Returns true if the date is a friday
First, require the date
library
require 'date'
Then create a new date instance with the current date. Here's an example
current_time = Time.now
year = current_time.year
month = current_time.month
day = current_time.day
date = Date.new(year, month, day)
date.friday?
=> true
Depending on your coding preferences, you could DRY this up even more
date = Date.new(Time.now.year, Time.now.month, Time.now.day)
=> #<Date: 2016-03-11 ((2457459j,0s,0n),+0s,2299161j)>
date.friday?
If you'd like to solve this without a Boolean method, (the ones that usually end in a question mark and return either true
or false
), such as when you're comparing to a database column, you can use the Date#wday
method. Keep in mind, this returns a number in the range (0..6) with 0 representing Sunday. This means that you want to pass in 5 to check for Friday.
if date.wday == 5
// Do something
end
Also, if you are working with business hours, it might be easiest to use the business_time
gem
You can also include the holidays
gem with business_time
.
First, install the gems
gem install business_time
gem install holidays
Then require the gem
require 'business_time'
require 'holidays'
Find out if today is a workday
Date.today.workday?
and is a holiday
You can now use something like this to determine if today is a holiday
Holidays.on(date, :us).empty?
and is between office working hours
The definition of office hours varies from person to person. There's no set-in-stone answer. However, with the business_time
gem, you can set configurations
BusinessTime::Config.beginning_of_workday = "8:30 am"
BusinessTime::Config.end_of_workday = "5:30 pm"
Sources
Ruby
http://ruby-doc.org/stdlib-2.1.1/libdoc/date/rdoc/Date.html#method-i-wday
http://ruby-doc.org/stdlib-2.1.1/libdoc/date/rdoc/Date.html#method-i-friday-3F
Gems
https://github.com/bokmann/business_time
https://github.com/holidays/holidays