Ranges with dates (in Groovy)
Published by peter December 1st, 2007 in groovy.During my previous ramblings with Groovy I didn't touch anything fancy in the Date/Calendar API; no need for it. But after reading a lengthy blogpost on the topic I just needed to have a look at it.
Consider the following code:
It prints a list of all Sundays between my and my wifes' birthday. Most of the 'magic' is done by the range operator (..) on which one can call all collection operations.
I somehow expected a more groovy like interface to the Calendar object; t.get( xxx ) just doesn't feel Groovy. Might be a nice little project to use method missing to make calls like t.dayOfWeek to work... maybe tomorrow ![]()
9 Responses to “Ranges with dates (in Groovy)”
- 1 Pingback on Dec 2nd, 2007 at 10:33 pm




















bd_daan = Date.parse("23-01-1980")
bd_peter = Date.parse("18-01-1979")
(bd_peter..bd_daan).each { |d| puts d if d.wday.zero? }
If you execute the code exactly as you pasted it; it wouldn't work. The Groovy code does work without any further 'import' or 'require'.
If I execute:
Did I import the wrong date??
There also is a slight difference in your ruby solution; which I could have used in my example... I build an array of the results and display it in a second each loop... could have been simpler:
Mind you, the use of a intermediate Calendar object is a bit overkill in this case... as is the use of the full blown Java date formatter. But the advantage is: full locale awareness when needed.
The code is mend to be run in a Rails environment e.g. script/console. Anyway.. not trying to prove a point, just checked to see if the same could be done in Ruby
Aha, makes sense
... I always tend to forget about the fact that Rails uses its' own date and time classes...
But hey, interesting... Rails' date object can actually be used in a range?
Indeed! That's the new thing I learned from this small excercise
As long as your class implements and succ you can use it in Range:
http://ruby-doc.org/core/classes/Range.html
Grr, <=> and succ that is..
With a little help from a colleague if figured out how to used Rails' date and time extensions when not running in Rails. Just load active_support: