I'm given some datetime format string that user entered, and need to check into what java.time temporals I can parse data in that format (within reason, I indend to support only the simpler cases for now).
Something along the lines of this table:
| Input Format | Expected Answer |
|---|---|
yyyy-MM |
java.time.YearMonth |
MM/dd/yyyy |
java.time.LocalDate |
yyyy:DD |
java.time.LocalDate (because of day-of-year data) |
HH:mm:ss |
java.time.LocalTime |
dd MM yyyy hh:mm:ssV |
java.time.ZonedDateTime |
Keeping in mind, that both the date format and the date are entered by the user, so these input formats are just examples, and they obviously can contain literals (but not optional parts, that's a relief).
So far I've only been able to come up with this tornado of ifs as a solution:
private static final ZonedDateTime ZDT = ZonedDateTime.of(1990, 10, 26, 14, 40, 59, 123456, ZoneId.of("Europe/Oslo"));
...
String formatted = externalFormatter.format(ZDT);
Class<?> type;
TemporalAccessor parsed = externalFormatter.parse(formatted);
if (parsed.isSupported(YEAR)) {
if (parsed.isSupported(MONTH_OF_YEAR)) {
if (parsed.query(TemporalQueries.localDate()) != null) {
if (parsed.query(TemporalQueries.localTime()) != null) {
if (parsed.query(TemporalQueries.zone()) != null) {
type = ZonedDateTime.class;
}
else if (parsed.query(TemporalQueries.offset()) != null) {
type = OffsetDateTime.class;
}
else {
type = LocalDateTime.class;
}
}
else {
type = LocalDate.class;
}
}
else {
type = YearMonth.class;
}
}
else {
type = Year.class;
}
}
else if (parsed.query(TemporalQueries.localTime()) != null) {
if (parsed.query(TemporalQueries.offset()) != null) {
type = OffsetTime.class;
}
else {
type = LocalTime.class;
}
}
Surely, there must be some better way, at least marginally? I will not limit myself to just using java.time, I also have the Joda-Time library available to me (although it's technically on legacy status), and I will not turn down a simpler code that uses the SimpleDateFormat if there is such an option.