-2

java.time.format.DateTimeParseException: Text '2018-03-29 16:15:30' could not be parsed at index 10

 DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                        OffsetDateTime date = 
 OffsetDateTime.parse(entry.getValue(), fmt);
                        predicates.add(cb.equal(root.get(entry.getKey()), date));
q112
  • 125
  • 3
  • OffsetDateTime javadoc says: A date-time with an offset from UTC/Greenwich in the ISO-8601 calendar system, such as 2007-12-03T10:15:30+01:00. Could it be that your date time formatter doesnt include time zone, and datetime? – Antonio Maria Sanchez Berrocal Apr 05 '18 at 13:01
  • 1
    This is a normal exception, because your text does not match your pattern. There is only enough data in temporal parsed with this format to construct a `LocalDate`. OffsetDateTime would need also `LocalTime` and `ZoneOffset`, which are missing. What's your use case here? – M. Prokhorov Apr 05 '18 at 13:03

1 Answers1

1

You created a DateTimeFormatter with the pattern "yyyy-MM-dd" (year-month-day), but your input also contains "hours:minutes:seconds" (2018-03-29 16:15:30).

But even if you use the correct pattern, this will still throw an exception:

// now the pattern matches the input
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
OffsetDateTime date = OffsetDateTime.parse("2018-03-29 16:15:30", fmt); // DateTimeParseException

That's because an OffsetDateTime also needs the UTC offset, and the input doesn't have it. You have some alternatives:

  1. parse it to a LocalDateTime:

    DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    LocalDateTime date = LocalDateTime.parse("2018-03-29 16:15:30", fmt);
    
  2. if you really need OffsetDateTime, you'll have to arbitrarialy choose some offset for it. Example:

    LocalDateTime date = // parse the LocalDateTime as above
    
    // use offset +02:00
    OffsetDateTime odt = date.atOffset(ZoneOffset.ofHours(2));
    

Or you can set a default value in the formatter:

DateTimeFormatter fmt = new DateTimeFormatterBuilder()
    // date/time pattern
    .appendPattern("yyyy-MM-dd HH:mm:ss")
    // use some offset as default (0 is UTC)
    .parseDefaulting(ChronoField.OFFSET_SECONDS, 0)
    .toFormatter();
OffsetDateTime odt = OffsetDateTime.parse("2018-03-29 16:15:30", fmt);
q112
  • 125
  • 3