"; */ ?>

Having Fun with Groovy Date Parsing

How do you convert a String to Date in Groovy? Well it’s simple:

   Date.parse( "yyyy-M-d", "2011-01-15" )

Now, let’s say I would like to shorten this: yes, it looks to long, remember the actual data I am interested in is “2011-01-15”, everything else means nothing really.. datawise.

Ok, so I can

  Date.metaClass.'static'.fromString = { str ->
    Date.parse( "yyyy-M-d", str )

which gives me a shorter representation ( less fluff around the actual data ):

  Date.fromString( "2011-01-15" )

That’s not bad, but I would like to take it further :) I am staging data ( domain objects ) in my Spock tests, and need as less fluff as possible => “only data matters”. So here it is, the geeky solution:

Create a DataParser:

  class DateParser {
    def static te = { str -> Date.parse( "yyyy-M-d", str ) }

Wherever you need parse dates, import it as ‘d’:

  import org.dotkam.util.date.DateParser as d

Now create your d.tes ( I mean dates :) ) as:

  d.te( "2011-01-05" )

//TODO: it can of course be extended with multiple formats