user860418
user860418

Reputation: 63

JodaTime how to parse correctly dd-MMM-yy to DataTime

The code snippet:

DateTimeFormatter dtf = new DateTimeFormatterBuilder()
        .appendDayOfMonth(2)
        .appendLiteral('-')
        .appendMonthOfYearShortText()
        .appendLiteral('-')
        .appendTwoDigitYear(2050)  // pivot point for correct interpretation of last two digits of year.
        .toFormatter();

        String strDate = "04-Feb-12";
        DateTime updateDate = dtf.parseLocalDate(strDate).toDateTimeAtStartOfDay();

And the output:

java.lang.IllegalArgumentException: Invalid format: "04-Feb-12" is malformed at "Feb-12"
at org.joda.time.format.DateTimeFormatter.parseLocalDateTime(DateTimeFormatter.java:821)
at org.joda.time.format.DateTimeFormatter.parseLocalDate(DateTimeFormatter.java:765)
...

I have tried as well:

DateTimeFormatter dtf = DateTimeFormat.forPattern("dd-MMMM-yy");

However in no way.

Thanks in advance.

Upvotes: 3

Views: 1961

Answers (1)

Brian Roach
Brian Roach

Reputation: 76908

You have a locale issue. The code you post works perfectly fine on my machine. I can, however, reproduce the exact error you're receiving if I change the locale to say Locale.FRENCH.

Change your builder to:

DateTimeFormatter dtf = new DateTimeFormatterBuilder()
    .appendDayOfMonth(2)
    .appendLiteral('-')
    .appendMonthOfYearShortText()
    .appendLiteral('-')
    .appendTwoDigitYear(2050)
    .toFormatter().withLocale(Locale.US);

Upvotes: 8

Related Questions