Search code examples
javajava-timedatetime-parsingzoneddatetimedatetimeformatter

String timestamp to Date in java


I want to convert a String timestamp "20221225182600Z+0100" to date in java without using simpledateformat

I am getting an error

Text '20221225182600Z+0100' could not be parsed at index 2

String dateString = "20221225182600Z+0100";
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssZ");
ZonedDateTime zonedDateTime = ZonedDateTime.parse(dateString,  dateTimeFormatter.ISO_OFFSET_TIME);
System.out.println(zonedDateTime);

Solution

  • Cannot parse nonsense

    I want to convert a String timestamp "20221225182600Z+0100" to date

    You cannot.

    Your input string apparently is a date, 2022-12-25, with time-of-day, 18:26. Plus two offsets from UTC.

    • Z near the end means an offset of zero hours-minutes-seconds from the temporal meridian of UTC.
    • The +0100 is an abbreviation of +01:00 which means one hour ahead of UTC.

    👉 Including two offsets with a date-time makes no sense. You cannot parse nonsense.

    Your situation is like asking to parse an amount of money in two currencies. “42 AUD USD” as an input is nonsense.

    Your input of 20221225182600Z+0100 is likely an error. I imagine one of those two offsets was intended while the other was an accident.

    By the way, I suggest always including the COLON in your offsets. While omission is officially permitted by the ISO 8601 standard, I have seen multiple protocols and libraries where the : between hours and minutes is expected.

    I also suggest educating the publisher of your data about the benefits of using only standard ISO 8601 formats for exchanging date-time values textually. See Wikipedia.

    The standard format for your input would be:

    • 2022-12-25T18:26:00Z
    • 2022-12-25T18:26:00+01:00

    Those two inputs represent two moments, 👉🏽 two different points on the timeline, an hour apart. The first moment arrived an hour behind the second moment.

    Parsing standard strings requires no formatting patterns. The java.time classes use ISO 8601 formats by default when parsing/generating text.

    • Instant.parse( "2022-12-25T18:26:00Z" )
    • OffsetDateTime.parse( "2022-12-25T18:26:00+01:00" )