'Convert string to OffsetDateTime in Java

I am trying to convert a string in OffsetDateTime but getting below error.

java.time.format.DateTimeParseException: Text '20150101' could not be parsed: Unable to obtain OffsetDateTime from TemporalAccessor: {},ISO resolved to 2015-01-01 of type java.time.format.Parsed

Code : OffsetDateTime.parse("20150101", DateTimeFormatter.ofPattern("yyyyMMdd"));

Expected output: OffsetDateTime object with date 20150101.

I really appreciate any help you can provide.

Thanks,



Solution 1:[1]

OffsetDateTime represents a date-time with an offset , for eg.

2007-12-03T10:15:30+01:00

The text you are trying to parse does not conform to the requirements of OffsetDateTime. See https://docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html

The string being parsed neither contains the ZoneOffset nor time. From the string and the pattern of the formatter, it looks like you just need a LocalDate. So, you could use :

LocalDate.parse("20150101", DateTimeFormatter.ofPattern("yyyyMMdd"));

Solution 2:[2]

Use a LocalDate instead of offsetDatetime for your case as you want to parse only date (no time/offset). The usage of offsetDatetime is very well discussed here

Solution 3:[3]

As Pallavi said correctly OffsetDateTime makes only in the context of a offset. Hence to go from a date string to an OffsetDateTime, you need a timezone!

Here is the recipe. Find yourself a Timezone, UTC or other.

ZoneId zoneId = ZoneId.of("UTC");   // Or another geographic: Europe/Paris
ZoneId defaultZone = ZoneId.systemDefault();

Make the LocalDateTime, works the same with LocalDate.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");    
LocalDateTime dateTime = LocalDateTime.parse("2022-01-28T14:29:10.212", formatter);

An offset makes only sense for a timezone and a time. For instance, Eastern Time hovers between GMT-4 and GMT-5 depending on the time of year.

ZoneOffset offset = zoneId.getRules().getOffset(dateTime);

Finally you can make your OffsetDateTime from both the time and the offset:

OffsetDateTime offsetDateTime = OffsetDateTime.of(dateTime, offset);

Hope this helps anyone.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Pallavi Sonal
Solution 2
Solution 3