Search code examples
javadatetimezone-offsetjava.time.instantdatetimeformatter

convert java timestamp string to java timestamp object


I have following timestamp string "2021010112:12:12.10:00" and I want to convert it to java.time.Instant.

The issue in parsing string through DateTimeFormatter is due to absence of time zone sign before last 4 digits. Logically it is yyyyMMddHH:mm:ss. and 10:00 is time zone offset e.g UTC+10:00, but issue is it does not have sign.

How can I parse this string to Instant object?


Solution

  • Not very elegant, but you could split the input by a dot. That would separate the datetime part from the offset and you can concatenate the desired (and required) sign with the value.

    This requires you to know which sign to apply! The code cannot guess it...

    Maybe write a method that takes this input String and a sign to be applied as arguments.

    Since it seems not possible to parse an unsigned String representation of an offset, you would need something like the following:

    public static void main(String[] args) {
        String timestamp = "2021010112:12:12.10:00";
        // provide a formatter that parses the datetime (the part before the dot)
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuuMMddHH:mm:ss");
        // split the timestamp String by the dot to separate datetime from offset
        String[] split = timestamp.split("\\.");
        // parse the datetime part using the formatter defined above
        LocalDateTime ldt = LocalDateTime.parse(split[0], dtf);
        // and build up an offset using offset part adding a plus sign
        ZoneOffset zoneOffset = ZoneOffset.of("+" + split[1]);
        // then create an OffsetDateTime from the LocalDateTime and the ZoneOffset
        OffsetDateTime result = OffsetDateTime.of(ldt, zoneOffset);
        // finally get an Instant from it
        Instant instant = result.toInstant();  // <--- INSTANT HERE
        // and print the values
        System.out.println(result + " = " + instant.toEpochMilli());
    }
    

    This outputs

    2021-01-01T12:12:12+10:00 = 1609467132000