How can I calculate the day of the week of a date in Ruby? For example, October 28 of 2010 is = Thursday
Ruby | DateTime parse() function DateTime#parse() : parse() is a DateTime class method which parses the given representation of date and time, and creates a DateTime object. Return: given representation of date and time, and creates a DateTime object.
You need to convert your string into Date object. For that, use Date#strptime . You can use Date#strftime to convert the Date object into preferred format.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With