How calculate the day of the week of a date in ruby? For example, October 28 of 2010 is = Thursday
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.
In your time object, use the property .wday to get the number that corresponds with the day of the week, e.g. If .wday returns 0, then your date is Sunday, 1 Monday, etc.
Well, I've never coded in ruby, but a quick google gives
time = Time.at(time) # Convert number of seconds into Time object.
puts time.wday # => 0: Day of week: 0 is Sunday
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's 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
As @mway said, you can use date.strftime("%A") on any Date object to get the day of the week.
If you're lucky Date.parse
might get you from String to day of the week in one go:
def weekday(date_string)
Date.parse(date_string).strftime("%A")
end
This works for your test case:
weekday("October 28 of 2010") #=> "Thursday"