How can I calculate the day of the week of a date in ruby?

Solution 1:

I have used this because I hated to go to the Date docs to look up the strftime syntax, not finding it there and having to remember it is in the Time docs.

require 'date'

class Date
  def dayname
     DAYNAMES[self.wday]
  end

  def abbr_dayname
    ABBR_DAYNAMES[self.wday]
  end
end

today = Date.today

puts today.dayname
puts today.abbr_dayname

Solution 2:

Take a look at the Date class reference. Once you have a date object, you can simply do dateObj.strftime('%A') for the full day, or dateObj.strftime('%a') for the abbreviated day. You can also use dateObj.wday for the integer value of the day of the week, and use it as you see fit.

Solution 3:

time = Time.at(time)    # Convert number of seconds into Time object.
puts time.wday    # => 0: Day of week: 0 is Sunday

Solution 4:

Date.today.strftime("%A")
=> "Wednesday"

Date.today.strftime("%A").downcase  
=> "wednesday"