Marco Fedele
Marco Fedele

Reputation: 2148

Cannot parse date with LocalDateTime

I'm trying to parse a date string using Java8 LocalDateTime without any success.

The exception is: DateTimeParseException: Text '28-APR-2015 01:25:00 PM' could not be parsed at index 3

The string to parse is: 28-APR-2015 01:25:00 PM and the pattern I'm currently using is dd-LLL-yyyy hh:mm:ss a

Where am I wrong?

Thank you

Adding example code:

String text = "28-APR-2015 01:25:00 PM";
DateTimeFormatter fromatter = DateTimeFormatter.ofPattern("dd-LLL-yyyy hh:mm:ss a");
try {
        String out = LocalDateTime.parse(text, formatter)
        System.out.println(out);
    } catch (DateTimeParseException e) {
        e.printStackTrace();
    }

Solved using the response from @Florin using:

    DateTimeFormatter tertiaryFormatter = new DateTimeFormatterBuilder()
        .parseCaseInsensitive().parseLenient().appendPattern("dd-LLL-yyyy hh:mm:ss a").toFormatter();

Upvotes: 1

Views: 3083

Answers (2)

SharpLu
SharpLu

Reputation: 1214

The problem is because of your time pattern issue. you need make sure your time format could matching with the pattern.

https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

enter image description here

Upvotes: 0

zacheusz
zacheusz

Reputation: 8842

MMM in English will be Apr

LLL in English will be 4

Please run this snippet - it will explain you a lot:

    asList("MMM", "LLL").forEach(ptrn
            -> System.out.println(ptrn + ": " + ofPattern(ptrn, Locale.ENGLISH).format(Month.APRIL))
    );
    Locale.setDefault(Locale.ENGLISH);
    String textM = "28-Apr-2015 01:25:00 PM";
    DateTimeFormatter formatterM = DateTimeFormatter.ofPattern("dd-MMM-yyyy hh:mm:ss a");
    System.out.println(LocalDateTime.parse(textM, formatterM));

    String textL = "28-4-2015 01:25:00 PM";
    DateTimeFormatter formatterL = DateTimeFormatter.ofPattern("dd-LLL-yyyy hh:mm:ss a");
    System.out.println(LocalDateTime.parse(textL, formatterL));

If you need to use APR then you need to build your own DateTimeFormatter using DateTimeFormatterBuilder and set parseCaseInsensitive option.

Upvotes: 1

Related Questions