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?
I think the best easy way in this case is to use parseToStringDate which a one of the Groovy JDK enhancements:
Example:
Hope this helps.
Date#parse
is deprecated . The alternative is :thereFore :
Note that SimpleDateFormat is an implementation of DateFormat
Below is the way we are going within our developing application.
The output looks like
In your example, we could adjust a bit to meet your need. If I were you, I will do:
I hope this would help you much.
The first argument to parse() is the expected format. You have to change that to
Date.parse("E MMM dd H:m:s z yyyy", testDate)
for it to work. (Note you don't need to create a new Date object, it's a static method)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. Edit: There is a Java port of the library called jChronic, you might want to check it out.
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:You can call it like this:
Googling around for Groovy ways to "cast" a
String
to aDate
, I came across this article: http://www.goodercode.com/wp/intercept-method-calls-groovy-type-conversion/The author uses Groovy metaMethods to allow dynamically extending the behavior of any class'
asType
method. Here is the code from the website.They provide a
Convert
class that wraps the Groovy complexity, making it trivial to add customas
-based type conversion from any type to any other:It's a convenient and powerful solution, but I wouldn't recommend it to someone who isn't familiar with the tradeoffs and pitfalls of tinkering with metaClasses.