Volodymyr Levytskyi
Volodymyr Levytskyi

Reputation: 3432

Why can't I parse this English date correctly in Java 8?

I want to execute a simple example to parse string to date with pattern.

String input = "Sep 31 2013";
LocalDate localDate = LocalDate.parse(input,
                DateTimeFormatter.ofPattern("MMM d yyyy"));

It throws exception:

Exception in thread "main" java.time.format.DateTimeParseException: Text 'Sep 31 2013' could not be parsed at index 0
    at java.time.format.DateTimeFormatter.parseResolved0(Unknown Source)
    at java.time.format.DateTimeFormatter.parse(Unknown Source)
    at java.time.LocalDate.parse(Unknown Source)
    at lambda.DateTime.main(DateTime.java:78)

I use java.time package from java 8.

Upvotes: 2

Views: 4835

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280170

I'm going to assume you have a non-english Locale. If you want to parse in English, use the appropriate Locale

String input = "Sep 31 2013";
LocalDate localDate = LocalDate.parse(input, DateTimeFormatter
            .ofPattern("MMM d yyyy").withLocale(Locale.ENGLISH));

Or any other English Locale: US, CANADA, UK, etc.

Alternatively, for your Locale, ru_RU, pass a Russian date String, ie. where Sep is in Russian so that it can be parsed appropriately

Upvotes: 7

Related Questions