Dark theme | Light theme

August 31, 2009

Groovy Goodness: Working with Dates

Thanks to Groovy's extensions to the JDK Date classes we can work with dates more easily. For example we can now add and subtract days with the plus() and minus() methods. And because this methods are mapped to the operators + and - we can write dense code.

Also the next() and previous() methods are implemented so we can use the ++ and -- operators to get to a next or previous day. We can even use the subscript operator ([]) to get date fields, because of the getAt() method Groovy adds to the Date class.

The Date class also contains parse() and format() methods to convert string to a date and to format a date into a string.

// Date.parse() to convert String to Date.
date = new Date().parse('yyyy/MM/dd', '1973/07/09')

// We can use [] or getAt() to get date fields.
assert 1973 == date[Calendar.YEAR]
assert 6 == date[Calendar.MONTH]
assert 9 == date.getAt(Calendar.DATE)

dateNext = date.clone()
datePrevious = date.clone()

// We can use the + and - operators to add or 
// subtract days.
nextDay = date + 1  // Or
previousDay = date - 1  // Or date.minus(1)

// ++ operator to move one day ahead.
dateNext++  // Or
assert dateNext == nextDay

// -- operator to move one day back.
datePrevious--  // Or datePrevious.previous()
assert datePrevious == previousDay

otherDate = new Date().parse('yyyy/MM/dd', '1973/07/21')
// Dates can be used in ranges.
assert 12 == (otherDate..<date).size()

// Set Locale to assert date formatting.

// Date.format() uses java.text.SimpleDateFormat.
assert '9 July, 1973' == date.format("d MMMM, yyyy")
assert '7/9/73' == date.getDateString()