Java: Unable to obtain LocalDate from TemporalAccessor

user7049000 picture user7049000 · Jul 26, 2017 · Viewed 31.1k times · Source

I am trying to change the format of a String date from EEEE MMMM d to MM/d/yyyy by, first, converting it into a LocalDate and then applying a formatter of a different pattern to the LocalDate before parsing it into String again.

Here's my code:

private String convertDate(String stringDate) 
{
    //from EEEE MMMM d -> MM/dd/yyyy

    DateTimeFormatter formatter = new DateTimeFormatterBuilder()
            .parseCaseInsensitive()
            .append(DateTimeFormatter.ofPattern("EEEE MMMM d"))
            .toFormatter();

    LocalDate parsedDate = LocalDate.parse(stringDate, formatter);
    DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("MM/d/yyyy");

    String formattedStringDate = parsedDate.format(formatter2);

    return formattedStringDate;
}

However, I get this exception message that I don't really understand:

Exception in thread "main" java.time.format.DateTimeParseException: Text 'TUESDAY JULY 25' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {DayOfWeek=2, MonthOfYear=7, DayOfMonth=25},ISO of type java.time.format.Parsed
    at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)

Answer

Pallavi Sonal picture Pallavi Sonal · Jul 26, 2017

The documentation for LocalDate says, that

LocalDate is an immutable date-time object that represents a date, often viewed as year-month-day. For example, the value "2nd October 2007" can be stored in a LocalDate.

In your case, the input String is missing an important component of LocalDate , i.e the year. What you have basically is month and day. So, you can use a class suited to that MonthDay. Using that your code can be modified to :

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                .parseCaseInsensitive()
                .append(DateTimeFormatter.ofPattern("EEEE MMMM d"))
                .toFormatter();

 MonthDay monthDay = MonthDay.parse(stringDate, formatter);
 LocalDate parsedDate = monthDay.atYear(2017); // or whatever year you want it at
 DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("MM/d/yyyy");

 String formattedStringDate = parsedDate.format(formatter2);
 System.out.println(formattedStringDate); //For "TUESDAY JULY 25" input, it gives the output 07/25/2017