Reputation: 33618
Look at examples:
yyyy-MM-dd -> java.time.temporal.ChronoUnit.DAYS
yyyy-MM-dd HH -> java.time.temporal.ChronoUnit.HOURS
yyyy;HH;ss -> java.time.temporal.ChronoUnit.SECONDS
yyyy;dd;MM -> java.time.temporal.ChronoUnit.DAYS
is there API to grab lowerest chrono unit from date time string format?
Upvotes: 4
Views: 471
Reputation: 328795
You could try to parse a predetermined date and check which units have values. I've written a quick example below which outputs:
yyyy-MM-dd Days
yyyy-MM-dd HH Hours
yyyy;HH;ss Seconds
yyyy;dd;MM ss n Nanos
Notes:
public static void main(String[] args) {
String[] formats = { "yyyy-MM-dd", "yyyy-MM-dd HH", "yyyy;HH;ss", "yyyy;dd;MM ss n" };
LocalDateTime test = LocalDateTime.of(1, 1, 1, 1, 1, 1, 1);
for (String f : formats) {
DateTimeFormatter format = DateTimeFormatter.ofPattern(f);
TemporalAccessor accessor = format.parse(test.format(format));
for (ChronoField unit : ChronoField.values()) {
if (testUnit(accessor, unit)) {
System.out.println(f + " " + unit.getBaseUnit());
break;
}
}
}
}
private static boolean testUnit(TemporalAccessor accessor, ChronoField unit) {
return accessor.isSupported(unit) && accessor.getLong(unit) == 1;
}
Upvotes: 4