Reputation: 327
I am fairly new to Groovy (but already loving it). I am not new to coding but haven't had much experience so far.
What am I doing? I am extracting certain information from an excel file to create a XML (SOAP) message from it to forward it to a web-service. Everything works fine so far except the Date conversion.
I am saving the string date to a var
odate = 'Wed Oct 31 00:00:00 CET 2012'
I need to reformat this Date into something like
"10/31/2012 10:09:00" (MM/dd/yyyy HH:mm:ss)
I have tried to parse the date as mentioned in another question but all I get is an exception.
String odate = 'Wed Oct 31 00:00:00 CET 2012'
def parsedodate = new Date().parse('E MMM dd H:m:s z yyyy', odate)
println parsedodate.format('MM/dd/yyyy h:m:s')
Exception thrown 31.10.2012 10:18:25 org.codehaus.groovy.runtime.StackTraceUtils sanitize
WARNUNG: Sanitizing stacktrace:
java.text.ParseException: Unparseable date: "Wed Oct 31 00:00:00 CET 2012"
Now after a little reading and some rounds of trial & error I found out that somehow the parse method seems to only interpret german dates. The following works after manually changing the string date to a german format (which is whre I am located).
String odate = 'Mi Okt 31 00:00:00 2012' //Mi = Wednesday, Okt = October, removed timezone
def parsedodate = new Date().parse('E MMM dd H:m:s yyyy', odate) // removed the z
println parsedodate .format('MM/dd/yyyy h:m:s')
However, I need the parser to accept the english date format. What do I do (wrong)?
Upvotes: 4
Views: 1760
Reputation: 583
Whole groovy solution for your problem would be:
import java.text.SimpleDateFormat
odate="Wed Oct 31 00:00:00 CET 2012"
englishPattern="E MMM dd H:m:s z yyyy"
SimpleDateFormat englishDateFormat = new SimpleDateFormat( englishPattern , Locale.ENGLISH);
//SimpleDateFormat germanDateFormat = new SimpleDateFormat( germanPattern , Locale.GERMAN);
Date englishDate = englishDateFormat.parse( odate );
//Date germanDate = germanDateFormat.parse( odate );
String englishOutput = englishDate .format( englishPattern );
//String germanOutput = germanDate .format( germanPattern );
englishDate.format("MM/dd/yyyy hh:mm:ss")
Upvotes: 1
Reputation: 5585
You will need to use some Java to access Locale aware SimpleDateFormat instance.
SimpleDateFormat englishDateFormat = new SimpleDateFormat( englishPattern , Locale.ENGLISH);
SimpleDateFormat germanDateFormat = new SimpleDateFormat( germanPattern , Locale.GERMAN);
Date englishDate = englishDateFormat.parse( odate );
Date germanDate = germanDateFormat.parse( odate );
String englishOutput = englishDate .format( englishPattern );
String germanOutput = germanDate .format( germanPattern );
Upvotes: 1