Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

DZone's Guide to

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

· Java Zone ·
Free Resource

Bring content to any platform with the open-source BloomReach CMS. Try for free.

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.

BloomReach CMS: the API-first CMS of the future. Open-source & enterprise-grade. - As a Java developer, you will feel at home using Maven builds and your favorite IDE (e.g. Eclipse or IntelliJ) and continuous integration server (e.g. Jenkins). Manage your Java objects using Spring Framework, write your templates in JSP or Freemarker. Try for free.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}