2

I tried this:

val x = java.time.Instant.parse("2022-12-12T09:51:09.681+0100")

But it throws an exception.

Exception in thread "main" java.time.format.DateTimeParseException: Text '2022-12-12T09:51:09.681+0100' could not be parsed at index 23
    at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2046)
    at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1948)
    at java.base/java.time.Instant.parse(Instant.java:395)
    at org.jetbrains.kotlin.idea.scratch.generated.ScratchFileRunnerGenerated$ScratchFileRunnerGenerated.<init>(tmp.kt:8)
    at org.jetbrains.kotlin.idea.scratch.generated.ScratchFileRunnerGenerated.main(tmp.kt:13)

What is wrong with the timestamp?

If I compare it to https://en.wikipedia.org/wiki/ISO_8601#Time_offsets_from_UTC I can not see an error.

This does not work either:

java.time.OffsetDateTime.parse("2022-12-12T09:51:09.681+0100")
ceving
  • 21,900
  • 13
  • 104
  • 178
  • 1
    Related: [this](https://stackoverflow.com/questions/7229603/simpledateformat-24h), [this](https://stackoverflow.com/questions/39133828/why-cant-offsetdatetime-parse-2016-08-24t183805-5070000-in-java-8) and many others. Don’t think this exact question has been asked before, though. – Ole V.V. Dec 12 '22 at 19:40
  • 1
    While the classes of java.time parse ISO 8601 format, they don’t parse *all* variants of ISO 8601. `Instant.parse()` accepts the offset given as `Z` (Zulu = zero), in later Java versions also as `+01:00` with a colon. To parse `+0100` without a colon you do need to specify the format using a `DateTimeFormatter`. – Ole V.V. Dec 12 '22 at 19:44

1 Answers1

3

Apply DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSxx") while parsing the given date-time string into an OffsetDateTime and then convert the obtained OffsetDateTime into an Instant if required.

import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String args[]) {
        DateTimeFormatter parser = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSxx");
        OffsetDateTime odt = java.time.OffsetDateTime.parse("2022-12-12T09:51:09.681+0100", parser);
        System.out.println(odt);

        // Convert to Instant
        Instant instant = odt.toInstant();
        System.out.println(instant);
    }
}

Output:

2022-12-12T09:51:09.681+01:00
2022-12-12T08:51:09.681Z

Learn more about the modern Date-Time API from Trail: Date Time.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110