tags:

views:

64

answers:

2

As the title states I have a string similar to:

"lorem ispom 12-DEC-2009 fsasdfsd 12:00"

OR

"the meeting is on 12-DEC-2009 at 13:00"

And I need to extract a Date with time from this.

What is an elegant and robust way of doing this in Groovy

A: 

Split the string at the blanks, use a java.util.SimpleDateFormat to convert every one of them to a date - until it doesn't complain (throw an exception). Same for the time part.

Something like

SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy")
Date dat
mystring.split(" ").each(){ part ->
  try {
    Date d=df.parse(part)
    dat = d
  }
  catch(ParseException e) { /*ignore*/ }
}
ammoQ
+2  A: 

I'd use a regex and the groovy "find" addition to the String class for this. Here's a simple regex that'll work for your test case. It could need to be tweaked depending on how lax you need to be on the input string.

import java.text.SimpleDateFormat

def extractDate(s) {
    s.find(/(\d\d-[A-Z]{3}-\d{4}).*(\d\d:\d\d)/) { full, date, time -> 
        return new SimpleDateFormat("dd-MMM-yyyy HH:mm").parse("$date $time")
    }
}
println extractDate("lorem ispom 12-DEC-2009 fsasdfsd 12:00")
println extractDate("the meeting is on 12-DEC-2009 at 13:00")

prints:

Sat Dec 12 12:00:00 CST 2009
Sat Dec 12 13:00:00 CST 2009
Ted Naleid
+1 and accepted. That's great thanks - just what I was looking for!
Pablojim