In this short tutorial, we’ll learn how to convert a String representing a date into a real Date object in Groovy.
However, we should keep in mind that this language is an enhancement of Java. Therefore, we can still use every plain old Java method, in addition to the new Groovy ones.
2. Using DateFormat
Firstly, we can parse Strings into Dates, as usual, using a Java DateFormat:
def pattern = "yyyy-MM-dd" def input = "2019-02-28" def date = new SimpleDateFormat(pattern).parse(input)
Groovy, however, allows us to perform this operation more easily. It encapsulates the same behavior inside the convenience static method Date.parse(String format, String input):
def date = Date.parse(pattern, input)
In short, that method is an extension of the java.util.Date object, and internally it instantiates a java.text.DateFormat upon every invocation, for thread safety.
2.1. Compatibility Issues
To clarify, the Date.parse(String format, String input) method is available since version 1.5.7 of Groovy.
Version 2.4.1 introduced a variant accepting a third parameter indicating a timezone: Date.parse(String format, String input, TimeZone zone).
So, going forward, they need to be included as a separate module, named groovy-dateutil:
<dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy-dateutil</artifactId> <version>2.5.6</version> </dependency>
There’s also version 3.0.0, but it’s currently in the Alpha stage.
3. Using JSR-310 LocalDate
Since version 8, Java introduced a whole new set of tools to handle with dates: the Date/Time API.
These APIs are better for several reasons and should be preferred over the legacy ones.
Let’s see how to exploit the java.time.LocalDate parsing capabilities from Groovy:
def date = LocalDate.parse(input, pattern)
We’ve seen how to transform a String into a Date in the Groovy language, paying attention the peculiarities between the specific versions.
As always, the source code and unit tests are available over on GitHub.