The error message is telling you that your DateTimeFormatter
is not able to parse the zone offset of +0000
at the end of your String
. That's because a DateTimeFormatter.ISO_LOCAL_DATE_TIME
just does not expect an offset, it is supposed to only parse
- year
- month of year
- day of month
- hour of day
- minute of hour
- second of minute
- fraction of second (and nanos)
That's it! No offset! No zone!.
But that also means it could perfectly parse everything until this offset in your example!
However, the String
is nearly formatted as an OffsetDateTime
, but unfortunately its ISO formatter expects an offset where hours and minutes are separated by a colon, e.g. +00:00
, and your String
does not have one.
java.time
grants you the possibility of building a custom formatter based on an exisiting one. That's why I mentioned above that everything apart from the offset could be parsed with a DateTimeFormatter.ISO_LOCAL_DATE_TIME
. You can take that one and attach an offset-x pattern which then parses your unseparated offset. Let's call it extending an existing formatter, here's an example:
public static void main(String[] args) {
// your example String
String someTimes = "2022-10-26T09:34:00.000+0000";
// build a suitable formatter by extending an ISO-formatter
DateTimeFormatter dtf = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
.appendPattern("xxxx")
.toFormatter(Locale.ENGLISH);
// then parse
LocalDate localDate = LocalDate.parse(someTimes, dtf);
// and print
System.out.println(localDate);
}
Output:
2022-10-26
It is always a good idea to create a formatter with a Locale
, but in most cases where exclusively numerical values are to be parsed, a formatter without a Locale
might be sufficient. That counts for DateTimeFormatter.ofPattern(String, Locale)
as well.