Question

If I have a Date object, I can get the day of the week from it as an integer, Monday = 1, Sunday = 7, like so:

date.cwday

Can I do the same thing to DateTime objects in Rails? I know that I can use strftime, but I'm doing some operations in a loop with a large data set with potentially hundreds of thousands of items, and would like to avoid extra conversions between strings and ints if possible.

Was it helpful?

Solution

The DateTime class inherits the cwday method from the Date class, so yes. I suggest visiting www.ruby-doc.org. Date and DateTime are in the standard (not core) library. Remember to choose the correct ruby version.

Also, if you're concerned about performance, there shouldn't be any performance penalty when using DateTime#cwday because the method is inherited from Date (not overridden). Note also that in ruby 1.8.7, both classes are written in pure ruby; while in 1.9, they're compiled C code (ruby-doc shows date_core.c as the source file). Your date code will likely run faster in 1.9.

OTHER TIPS

I think so yes

1.9.3-p392 :002 > DateTime.new
 => Mon, 01 Jan -4712 00:00:00 +0000
1.9.3-p392 :003 > _.cwday
 => 1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top