Home > Blockchain >  How to parse a time stamp with numeric time zone offset?
How to parse a time stamp with numeric time zone offset?

Time:12-13

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")

CodePudding user response:

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.

  • Related