Groovy Goodness: Create New Date or Calendar from Existing and Set Property Value
Join the DZone community and get the full member experience.Join For Free
Since Groovy 2.2 we can create a new
Calendar object from an existing
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
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.
Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
How To Use Git Cherry-Pick to Apply Selected Commits
Deploying Smart Contract on Ethereum Blockchain
From CPU to Memory: Techniques for Tracking Resource Consumption Over Time