It's common knowledge that java.util.Date
has undesireable qualities and should be avoided whenever possible by developers, especially now that a proper Date/Time API exists within Java SE. Despite its faults, however, there are actually some features of the Groovy language that may be encouraging the continued use of java.util.Date
.
1. It is always imported
Groovy imports the java.util
package by default because, more often than not, code will need something defined within that package. Date, of course, being in that package, becomes readily available for use. I've become accustomed to invoking new Date()
and Date.parse(dateStr)
without even thinking about my import statements.
The Java 8 Date/Time API is a different story. I often write my Groovy scripts without a full-featured IDE, so I have to manually add imports--usually after some thrown Exception gently reminds me to.
def dayOfWeek = LocalDate.now().get(ChronoField.DAY_OF_WEEK)
"MissingPropertyException? Ah yes, I forgot to import the java.time
pacakge."
import java.time.*
def dayOfWeek = LocalDate.now().get(ChronoField.DAY_OF_WEEK)
"Again? Oh, that's right; ChronoField
is not in java.time
."
import java.time.*
import java.time.chrono.ChronoField
def dayOfWeek = LocalDate.now().get(ChronoField.DAY_OF_WEEK)
"Oh, come on! When am I going to remember that ChronoField is not in java.time.chrono
but in java.time.temporal
?"
2. It has a DSL
DSL support is one of Groovy's strengths. One out-of-the-box DSL Groovy provides is for manipulating dates and durations: TimeCategory. The downside to this DSL is that the expressions require and yield java.util.Date
instances.
3. It has goodies in the Groovy JDK
The Groovy JDK is another feature of Groovy that makes the language a pleasure to use. Specifically, the Groovy JDK adds methods to the core Java types that you wish they always had. Date is no exception. Its more useful extension methods include:
static Date parse(String format, String input)
- no more messing around with explicit instances ofSimpleDateFormat
, thank you very muchString format(String format)
- dittoDate clearTime()
- for the occassions when you want to use Date as just a date
Furthermore, certain extension methods correspond to particular operators, making Date manipulation even more simpler, like the plus
and minus
methods allow you to add or subtract days from a given Date instance for quick-and-easy calculations.
To address these issues, I've created a library called Goodtimes with the simple aim to bring comprable support for the new Java 8 Date/Time types that exist for the Groovy types. Let's take a look at how Goodtimes can be used to offset some of java.util.Date's distinct advantages listed above.