Search

Dark theme | Light theme

June 14, 2010

Groovy Goodness: Use the set Method to Define a Date or Calendar Value

In a previous post we learned about the new subscript operator support in Groovy 1.7.3 for setting Date or Calendar values. But we have other new ways in Groovy 1.7.3: we can use a set() method to set the values. The method accepts a Map with the following keys: year, month, date, hourOfDay, minute and second. The keys are used to set the according values of the Date or Calendar object.

import static java.util.Calendar.*

def cal = Calendar.instance
cal.set(year: 2010, month: JULY, date: 9)

assert 'Birthday @ 2010-7-9' == 'Birthday @ ' + cal.format('yyyy-M-d')
assert FRIDAY == cal[DAY_OF_WEEK]

def date = new Date()
date.set(hourOfDay: 12, minute: 0, second: 0, year: 2010, month: JUNE, date: 1)

assert '12:00:00' == date.format('HH:mm:ss')
assert 2010 == date[YEAR]
assert JUNE == date[MONTH]
assert 1 == date.getAt(DATE)