Java 8+ ISO8601 date formatting with LocalDate, Instant and DateTimeFormatter

ISO8601 datetime formats are commonly used especially when storing dates as Strings. Java 8’s java.time.format.DateTimeFormatter has a predefined formatter to format as ISO8601, DateTimeFormatter.ISO_INSTANT, but applying it to a DateTime instance gives an exception:

String formattedDate = DateTime.now().format(DateTimeFormatter.ISO_INSTANT);
java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: InstantSeconds
at java.time.LocalDate.get0(LocalDate.java:680)

If you check the JavaDocs (here) there is a comment that states:

"This is a special case formatter intended to allow a human readable form of an Instant"

Changing this code to use an Instant instead:

DateTimeFormatter.ISO_INSTANT.format(Instant.now());

works as expected:

2021-04-25T22:09:40.690Z