A Groovy First Monday

22 September 2010

The new K-Prep website is implemented in Grails now, so I was looking for a Groovy way to let the computer do the heavy lifting of figuring out dates for each week (starting with the first Monday) of the school year and matching them to a list of themes.

I got the algorithm working in about 8 lines of Groovy code, and then generalized it a bit more for you here to allow you to ask for any day of any week of any month. e.g. 3rd Wednesday in December.

To get the date for the 3rd Wednesday in December, my call looks like this:

dayByWeek(2010, DECEMBER, 2, WEDNESDAY, 0)

And the implementation looks like this:

import static java.util.Calendar.*

def dayByWeek = { year, month, week, day, shift ->
    def c = Calendar.instance
    c.minimalDaysInFirstWeek = c.firstDayOfWeek + 7 - day
    c[YEAR] = year
    c[MONTH] = month
    c[WEEK_OF_MONTH] = week + 1 + (shift?:0)
    c[DAY_OF_WEEK] = day

The shift parameter allows me to optionally start a theme on the previous week in cases where that day is the end of the previous month. The static import allows me to conveniently refer to the Calendar constants without qualifying them, and finally, setting the minimalDaysInFirstWeek allows days early or late in the week to still be found when the Calendar would have otherwise preferred a longer week to start searching.

Filed Under: Computers Java Web-Dev