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

Start coding something amazing with our library of open source Cloud code patterns. Content provided by IBM.

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.

Use this tool to look at the contents of GitHub and classify code based on the programming language used.  Content provided by IBM Developer.

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 }}