June 14, 2010

Groovy Goodness: Create New Date from Old Date with Updates

Groovy 1.7.3 adds the updated() method to the Date and Calendar classes. We pass a Map as parameter to this method to define which fields are updated. The fields that are not mentioned are unchanged. The result is a new Date or Calendar object, our original object stays the same.

import static java.util.Calendar.*

def cal = Calendar.instance
def calNextMonth = cal.updated(month: cal[MONTH] + 1, year: 2012)

assert JANUARY == calNextMonth[MONTH]
assert 2013 == calNextMonth[YEAR]

def date = new Date()
date.set(year: 2011, month: MAY, date: 5)
def dateTenYearsAgo = date.updated(year: date[YEAR] - 10)

assert '2011-5-5' == date.format('yyyy-M-d')
assert '2001-5-5' == dateTenYearsAgo.format('yyyy-M-d')