Reputation: 2516
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
Upvotes: 2
Views: 1831
Reputation: 79075
The accepted answer has correctly explained the root cause and the solution. However, note that your date-time string 26.06.2019T00:00:00.123+03:00
has a time zone offset (e.g. +03:00), not a time zone ID (e.g. America/New_York
); therefore, it makes more sense to parse it into an OffsetDateTime
.
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(
"dd.MM.uuuu'T'HH:mm:ss.SSSXXX", Locale.ROOT);
OffsetDateTime.parse("26.06.2019T00:00:00.123+03:00", dtf);
Learn more about the modern Date-Time API from Trail: Date Time
Upvotes: 1
Reputation: 13933
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.
Upvotes: 5