I am trying to parse a string to an OffsetDateTime but getting the following error:
Unhandled exception.
java.time.format.DateTimeParseException: Text '26122019' could not be parsed: Unable to obtain OffsetDateTime from TemporalAccessor: {},ISO,Europe/Berlin resolved to 2019-12-26 of type java.time.format.Parsed
Example of the string I am attempting to parse looks like 26122019 and the value in the database looks like 2018-08-31.
I got another error prior that sent me on this path when while writing a JPA query for these values @Param("filterEndDate") OffsetDateTime filterEndDate,.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMyyyy").withZone(ZoneId.of("Europe/Berlin"));
OffsetDateTime fromDate = OffsetDateTime.parse(filterFromDate,formatter);
OffsetDateTime toDate = OffsetDateTime.parse(filterEndDate,formatter);
then I adjusted my code
DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendPattern("ddMMyyyy")
.parseDefaulting(ChronoField.NANO_OF_DAY, 0)
.toFormatter()
.withZone(ZoneOffset.UTC);
and got the following error:
Caused by: java.time.DateTimeException: Unable to obtain OffsetDateTime from TemporalAccessor: {InstantSeconds=1577318400},ISO,Z resolved to 2019-12-26T00:00 of type java.time.format.Parsed
-----update 1----
code
LocalDate fromDate = LocalDate.parse(filterFromDate,DateTimeFormatter.ofPattern("ddMMyyyy"));
error
java.time.format.DateTimeParseException: Text '2019-12-20' could not be parsed at index 2
I am showing two ways.
To me the simple way would go like this:
String filterFromDate = "26122019";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMyyyy");
OffsetDateTime fromDate = LocalDate.parse(filterFromDate, formatter)
.atStartOfDay(ZoneOffset.UTC)
.toOffsetDateTime();
System.out.println(fromDate);
Output from this snippet is:
2019-12-26T00:00Z
Since your string contains a date and no time of day and no offset, I am parsing into a LocalDate. Then I perform the conversion to OffsetDateTime afterwards.
The way you tried can be made to work with just a simple adjustment:
DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendPattern("ddMMyyyy")
.parseDefaulting(ChronoField.NANO_OF_DAY, 0)
.parseDefaulting(ChronoField.OFFSET_SECONDS, 0)
.toFormatter();
OffsetDateTime fromDate = OffsetDateTime.parse(filterFromDate, formatter);
The result is the same as before. java.time distinguishes between an offset and a time zone. In many places an offset can be used where a time zone is required, but not here. Your call to withZone() provided a default time zone, but no default offset. Instead I am using .parseDefaulting(ChronoField.OFFSET_SECONDS, 0) to establish a default offset.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With