Cherry
Cherry

Reputation: 33618

How get lowerest chrono unit from date format?

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

Answers (1)

assylias
assylias

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:

  • it relies on the fact that the units are in ascending order within the ChronoField enum.
  • it will work for built-in units (year, month, day, second, nanos) but may not give the result you want for other fields such as week-based fields or milli/microseconds fields for example.
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

Related Questions