Joda date formatter

12,675

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.

Share:
12,675
Hubert Solecki
Author by

Hubert Solecki

Updated on June 04, 2022

Comments

  • Hubert Solecki
    Hubert Solecki almost 2 years

    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.

  • Hubert Solecki
    Hubert Solecki over 9 years
    Thank you so much for that answer. It's really complete.