fardin fardin - 2 years ago 75
Ruby Question

Rails - Determine the day of the week


Fri, 11 Mar 2016 19:34:10 +0000

How can I determine the day of the week. For example, if
is Friday(just the day of the week, regardless of the date)?

DateTime.current == DateTime.parse("Friday")
Won't work because
Fri, 11 Mar 2016 00:00:00 +0000
which is not the same.

How can I check whether only the date or only the time equals to a specific value?

Thanks in advance!

Basically I want to see if
is not a weekend nor a public holiday and is between office working hours

Answer Source

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)
=> 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)>

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

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


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"








Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download