Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing ZonedDateTime with Java 8 DateTimeFormatter

Tags:

java

java-8

I am trying to create a ZonedDateTime with a DateTimeFormatter by using the following pattern "dd-mm-yyyy'T'HH:mmZ":

public static ZonedDateTime timeFromDayMonthYearHHmmTZ(String dateTime){
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy'T'HH:mmZ");
        return ZonedDateTime.parse(dateTime, formatter);
    }

Using the previous code, the following expression parses correctly:

ZonedDateTime dateTime1 = ZonedDateTimeUtils.dateTimeFromDayMonthYearHHmmTZ("25-01-2018T15:30-0100");

However, the next expression generates an exception (notice the : in the TZ offset):

ZonedDateTime dateTime2 = ZonedDateTimeUtils.dateTimeFromDayMonthYearHHmmTZ("25-01-2018T15:30-01:00");

My understanding is that Z in the pattern "dd-mm-yyyy'T'HH:mmZ" should cover both cases? However I am getting the following exception:

java.time.format.DateTimeParseException: Text '25-01-2018T15:30-01:00' could not be parsed at index 16

Ideally I would like to have a flexible solution where I can parse both patterns.

like image 777
BigONotation Avatar asked Jan 27 '26 06:01

BigONotation


1 Answers

From what I found, there seems to definitly be a problem with Z.

I found this question and in the answer, it uses XXX for the offset. I tried it and it is working. I checked a few variations like X,XX,Z,ZZ and ZZZ, but only XXX worked fine.

The complete pattern is dd-MM-yyyy'T'HH:mmXXX

like image 191
XtremeBaumer Avatar answered Jan 29 '26 18:01

XtremeBaumer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!