Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

date

ruby

How can I calculate the day of the week of a date in Ruby? For example, October 28 of 2010 is = Thursday

like image 640
Mangano Avatar asked Oct 28 '10 15:10

Mangano


People also ask

How do you parse a date in Ruby?

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.

How do I change the date format in Ruby?

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.


2 Answers

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 
like image 124
steenslag Avatar answered Sep 22 '22 13:09

steenslag


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.

like image 31
mway Avatar answered Sep 18 '22 13:09

mway