k88
k88

Reputation: 1934

Java DateTimeFormatter

I am trying to read in a CSV file where I need to parse a certain date value. However I get a DateTimeParseException I cannot place.

The field I am trying to read is a date field that looks like this: 08-May-2016

The code I use: LocalDate date = LocalDate.parse(row[3], DateTimeFormatter.ofPattern("d-M-yy")); where row[3] is the field I read from the CSV file.

The exception I get: Text '08-May-16' could not be parsed at index 3

Am I wrong to think that d-M-yy should be able to read single-digit, double-digit and letter representations for the month of the year?

EDIT: I have tried MMM-MM-M for the month as well as dd-d for the day field. I still get the same exception.

Upvotes: 1

Views: 1635

Answers (2)

anders
anders

Reputation: 824

The problem here is that you don't supply a Locale when you create your DateTimeFormatter - you need to use a Locale that supports that format:

System.out.println(LocalDate.parse("08-May-2016", DateTimeFormatter.ofPattern("dd-MMM-yyyy", Locale.ENGLISH)));

Output:

2016-05-08

This doesn't work:

System.out.println(LocalDate.parse("08-May-2016", DateTimeFormatter.ofPattern("dd-LLL-yyyy", Locale.ENGLISH)));

Output:

Exception in thread "main" java.time.format.DateTimeParseException: Text '08-May-2016' could not be parsed at index 3
    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
    at java.time.LocalDate.parse(LocalDate.java:400)

Upvotes: 3

mort
mort

Reputation: 13588

Am I wrong to think that d-M-yy should be able to read single-digit, double-digit and letter representations for the month of the year?

Yes. Your pattern would parse dates of the form 1-5-16 correctly, but not 10-May-2016. Try dd-MMM-yyyy.

Upvotes: 2

Related Questions