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" )

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

7 comments

  1. Hey thanks, this may be fun for you but it was very helpful to a noob like me :)

  2. Date.parse is deprecated ;-(

  3. meh,
    I am not sure where you get your intel, but “Date.parse” is a static method that is a published API: “http://groovy.codehaus.org/groovy-jdk/java/util/Date.html#parse(java.lang.String, java.lang.String)” that is in no way depreciated.

  4. Yes it is, you should use parseDateFormat.parse as recommended in the java API

  5. I know this thread of comments is a bit old, but if my understanding is correct, Date.parse is a Groovy wrapper for SimpleDateFormat in Java. That is to say that in Groovy, Date.parse is NOT deprecated, but I believe the method by the same name IS deprecated in Java. Hopefully that helps…

  6. Apparently, it’s Eclipse that says that Date.parse() is deprecated… Not the doc from Groovy…

tell me something...
  1. (required)
  2. (valid email - optional)
  3. Captcha
  4. (required)