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:
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);
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);