Skip to content
Advertisement

OffsetTime.parse causes an exception with ISO_TIME formatter

I am trying to convert between LocalTime and strings by using the ISO_TIME formatter, but I get an exception. My Code is like:

        LocalTime some_time = LocalTime.of( 10, 10, 10 );
        String time_format = some_time.format(DateTimeFormatter.ISO_TIME);
        System.out.println(OffsetTime.parse(time_format, DateTimeFormatter.ISO_TIME ));

the last line throws an exception:

Exception in thread "main" java.time.format.DateTimeParseException: Text '10:10:10' could not be parsed: Unable to obtain OffsetTime from TemporalAccessor: {},ISO resolved to 10:10:10 of type java.time.format.Parsed
    at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855)
    at java.time.OffsetTime.parse(OffsetTime.java:327)

Why is this happening and how could I solve this problem?

Thanks in advance for any help, Anas

Advertisement

Answer

This is happening because, well, it’s right there in the name. An OffsetTime contains both an actual time (such as ‘5 minutes past midnight’) as well as a zone offset, such as ‘+01.00’. (as in, in some location that is currently 1 hour later than UTC time, such as mainland europe in the winter).

in contrast, a LocalTime contains only an actual time, not an offset.

Converting from a local time (be it in string form or as a LocalTime object) to an OffsetTime is therefore not possible; OffsetTime has no idea which offset you’d want.

What you can do is something like this:

LocalTime time = LocalTime.parse("10:10:10", DateTimeFormatter.ISO_TIME);
OffsetTime atPlus1 = time.atOffset(ZoneOffset.ofHours(+1));

Here you get the time from the string, and then programmatically set the offset.

Let me repeat: the string 10:10:10 fundamentally is not an offset time. You can convert that string to an offset time as well as you can convert an apple into a banana.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement