Hubert Solecki
Hubert Solecki

Reputation: 2761

Joda date formatter

Does anyone know how to parse a date such as: Mon Aug 04 16:07:00 CEST 2014 to dd/MM/YYYY HH:MM:SS using DateTime formatter from Joda. I've tried that:

final DateTimeFormatter sdf = DateTimeFormat.forPattern(DATE_FORMAT);
DateTime lastDateOnline = sdf.parseDateTime(lastCommunicationToDisplay.getDateOnLine().toString());
return lastDateOnline.toString();

DATE_FORMAT = dd/MM/YYYY HH:MM:SS and lastCommunicationToDisplay.getDateOnLine().toString() = Mon Aug 04 16:07:00 CEST 2014

I can't find clear explanations about that library. I'm requested to use that instead of SimpleDateFormat because it's not threadsafe.

Upvotes: 2

Views: 12703

Answers (1)

Cristina_eGold
Cristina_eGold

Reputation: 1553

Solutions

If all you have to do is convert a LocalDate to a string respecting the pattern: "dd/MM/YYYY HH:mm:ss", then you can do it in a simpler way, using the overloaded toString() methods on LocalDate:

a) the one which receives the format string directly:

LocalDate date = lastCommunicationToDisplay.getDateOnLine();
System.out.println(date.toString("dd/MM/YYYY HH:mm:ss"));

b) the one which receives a DateTimeFormatter initialized with the aforementioned string:

DateTimeFormatter dtf = DateTimeFormat.forPattern("dd/MM/YYYY HH:mm:ss");
LocalDate date = lastCommunicationToDisplay.getDateOnLine();
System.out.println(date.toString(dtf));

What went wrong in your code

The format string you are using is not compatible with the date string you are sending as input. The way you used DateTimeFormatter is used for parsing strings that are in that format to LocalDates, not the other way around.

The format would be appropriate if your input string would look like the following: 04/08/2014 22:44:33

Since yours looks differently, the following value of the format is compatible (provided your timezone is always CEST):

DATE_FORMAT = "E MMM dd HH:mm:ss 'CEST' YYYY";

So the entire code should look like this:

String dateString = "Mon Aug 04 16:07:00 CEST 2014";
DateTimeFormatter dtf = DateTimeFormat.forPattern("E MMM dd HH:mm:ss 'CEST' YYYY");
LocalDate date = dtf.parseLocalDate(dateString);
System.out.println(date.toString("MM/dd/yyyy")); // or use toString(DateTimeFormatter) and use your pattern with a small adjusment here (dd/MM/YYYY HH:mm:ss)

However, I recommend one of the first 2 suggestions.

Upvotes: 8

Related Questions