brain storm
brain storm

Reputation: 31252

java 8 datatime parse error

I am trying to convert a string to LocalDate object. but I get the following error.

private LocalDate getLocalDate(String year) {
        String yearFormatted = "2015-01-11";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYY-MM-dd");
        LocalDate dateTime = LocalDate.parse(yearFormatted, formatter);
        return  dateTime;
    }

here is the error

Caused by: java.time.format.DateTimeParseException: Text '2015-01-11' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {DayOfMonth=11, WeekBasedYear[WeekFields[SUNDAY,1]]=2015, MonthOfYear=1},ISO of type java.time.format.Parsed
    at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920) ~[na:1.8.0_102]
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855) ~[na:1.8.0_102]
    at java.time.LocalDate.parse(LocalDate.java:400) ~[na:1.8.0_102]

Upvotes: 1

Views: 2584

Answers (1)

Anonymous
Anonymous

Reputation: 86296

As the documentation says, the capital Y in a format pattern is for week-based-year, that is, the year that the week number belongs to. This is not always the same as the calendar year (though most often it is). Java is smart enough to recognize that it cannot be sure to get a date out of week-based year, month and day-of-month, so it throws the exception instead.

Since the format of your string agrees with the default LocalDate format (ISO 8601), the simplest solution is to drop the formatter completely and just do:

    LocalDate dateTime = LocalDate.parse(yearFormatted);

With this change, you method returns a date of 2015-01-11 as I think you had expected. Another fix is to replace YYYY with either lowercase yyyy for year-of-era or uuuu for a signed year (where 0 is 1 BC, -1 is 2BC, etc.).

Upvotes: 3

Related Questions