November 18, 2013

Groovy Goodness: Create New Date or Calendar from Existing and Set Property Value

Since Groovy 2.2 we can create a new Date or Calendar object from an existing Date and Calendar object and directly change property values. We must use the copyWith() method and we pass a map with property names and values as an argument. The newly created object will have the old values for properties from the original object and the properties set in the map are overridden.

The following code shows the new copyWith() method:

import static java.util.Calendar.NOVEMBER

// Create original date.
def date = new Date().clearTime()
date.set(year: 2013, month: NOVEMBER, date: 18)

// Use copyWith to get new Date and 
// immmediatelly set year to 2014.
def yearLater = date.copyWith(year: 2014)

assert yearLater.format('dd-MM-yyyy') == '18-11-2014'

// Also works for Calendar.
def cal = Calendar.instance
cal.set(year: 2013, month: NOVEMBER, date: 10)

// Create new Calendar with new date value.
def newCalendar = cal.copyWith(date: 18)

assert newCalendar.format('dd-MM-yyyy') == '18-11-2013'

Code written with Groovy 2.2.