Parse ZonedDateTime from String containing milliseconds

Andrey Yaskulsky :

I need to get ZonedDateTime from the String of the following format:

"26.06.2019T00:00:00.123+03:00"

This format seems to be a standard one, so I used the following code to parse ZonedDateTime from the string:

ZonedDateTime.parse("26.06.2019T00:00:00.123+03:00");

However, I get an exception:

Exception in thread "main" java.time.format.DateTimeParseException: Text '26.06.2019T00:00:00.123+03:00' could not be parsed at index 0
Matt :

The format you are using is not a standard format since you are using dd.mm.yyyy for the date instead of yyyy-mm-dd. Therefore it does not work with the default formatter used by parse().

You can easily set up a custom DateTimeFormatter for your special case:

String pattern = "dd.MM.yyyy'T'HH:mm:ss.SSSXXX";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern);

String input = "26.06.2019T00:00:00.123+03:00";
ZonedDateTime zonedDateTime = ZonedDateTime.parse(input, dtf);

The output of System.out.println(zonedDateTime) is then the correct ISO-format:

2019-06-26T00:00:00.123+03:00

As per Jesper's comment, I would advise you to use the actual standard format and to try to convince whoever is supplying you those string to use the actual ISO format as well.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=142801&siteId=1