views:

73

answers:

3

I am coding this with Groovy

I am currently trying to convert a string that I have to a date without having to do anything too tedious.

String theDate = "28/09/2010 16:02:43";
def newdate = new Date().parse("d/M/yyyy H:m:s", theDate)

Output:

Tue Aug 10 16:02:43 PST 2010

The above code works just fine, however when my string changes to something like:

String testDate = "Tue Aug 10 16:02:43 PST 2010"
def newerdate = new Date().parse("d/M/yyyy H:m:s", testDate)

It tells me that "there is no such value for Tue". I tried to throw an 'E' in the parse for the date but it said the date was not able to be parsed.

Can someone explain how I should go about parsing the second example?

A: 

Try this:

def newerdate = new Date().parse("E MMM dd H:m:s z yyyy", testDate)

Here are the patterns to format the dates

gcores
Thank you for your time and help gcores. Also thank you for the link :)
StartingGroovy
+3  A: 

The first argument to parse() is the expected format. You have to change that to new Date().parse("E MMM dd H:m:s z yyyy", testDate) for it to work.

If you don't know in advance what format, you'll have to find a special parsing library for that. In Ruby there's a library called Chronic, but I'm not aware of a Groovy equivalent.

Mark Thomas
Thank you Mark, I was messing with it for awhile and didn't realize that I needed the 'MMM' instead I only tried 'M'.
StartingGroovy
+1  A: 

JChronic is your best choice. Here's an example that adds a .fromString() method to the Date class that parses just about anything you can throw at it:

Date.metaClass.'static'.fromString = { str ->
    com.mdimension.jchronic.Chronic.parse(str).beginCalendar.time
}

You can call it like this:

println Date.fromString("Tue Aug 10 16:02:43 PST 2010")
println Date.fromString("july 1, 2012")
println Date.fromString("next tuesday")
ataylor
Thank you for the information :) This will definitely come in handy for the future
StartingGroovy