2
DateTimeFormatter formatter2 = new DateTimeFormatterBuilder()
                    .appendPattern("h:mm a z - d MMMM")
                    .toFormatter()
                    .withLocale(Locale.US);

            String test = "7:00 PM EST - 14 April";
LocalDateTime date2 = LocalDateTime.parse(test, formatter2);

It throws this exception

java.time.format.DateTimeParseException: Text '7:00 PM EST - 14 April' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {DayOfMonth=14, MonthOfYear=4},ISO,America/New_York resolved to 19:00 of type java.time.format.Parsed

But you can see that it correctly parsed out all the components. What's the issue?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
erotsppa
  • 14,248
  • 33
  • 123
  • 181

1 Answers1

3

The issue is that the construction of a LocalDateTime requires a year to be present, but your time string does not.

You can instruct the DateTimeFormatterBuilder to default to some value if some element is absent, using parseDefaulting.

DateTimeFormatter formatter2 = new DateTimeFormatterBuilder()
    .parseDefaulting(ChronoField.YEAR, 2023)
    .appendPattern("h:mm a z - d MMMM")
    .toFormatter()
    .withLocale(Locale.US);
MC Emperor
  • 22,334
  • 15
  • 80
  • 130