BigONotation
BigONotation

Reputation: 4538

Parsing ZonedDateTime with Java 8 DateTimeFormatter

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.

Upvotes: 3

Views: 1825

Answers (2)

XtremeBaumer
XtremeBaumer

Reputation: 6435

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

Upvotes: 6

Anthony Cannon
Anthony Cannon

Reputation: 1273

For this error to be solved, you need to use X instead of Z, so... "dd-MM-yyyy'T'HH:mmX"

If you look at the java docs it explains that:

  • Z allows for -0800
  • X allows for one of the three -08; -0800; -08:00

So for your case being 25-01-2018T15:30-01:00, you need to use the latter.

Upvotes: 0

Related Questions