W3C ISO 8601
That document is a self-declared “profile” of the ISO 8601 standard, not the standard itself.
This seems to be such a common use case, im surprised its not part of the standard library
The java.time classes do indeed use the ISO 8601 formats by default when parsing text.
There is no universal parser because context matters. A year, a year-month, a date, a time-of-day, a date with time-of-day, a date with time-of-day with offset, a date with time-of-day with time zone, are all different animals. You would not ordinarily expect values of different types to arrive arbitrarily.
If you really do have such a collection of arbitrary types, then simply perform a series of parse attempts. Trap for the DateTimeParseException
exception. If parsing with one java.time class fails, move on to the next java.time class.
You said:
It should return a ZonedDateTime, with missing fields set to 0 as specified in the W3C spec.
How would you turn a year-only value into a ZonedDateTime
object? What should be the month and day values? Zero is not acceptable there. What time zone? You’ll need to specify your desired zone. What time-of-day? Zeros for time does not work as not all days in some zones start the day at 00:00:00.
For these reasons, a universal parser is not possible. You need to perform the parsing according to the business rules of your particular app for your particular input data.
You can come closer to your desired universal parser by establishing default values with the DateTimeFormatterBuilder
class. See Answer by Avinash.