Search code examples
javatimelocaldate

Calculate Seconds between two LocalDates in Java


i am trying to calculate seconds between two LocalDates. Now this is actually giving me a hard time as this code snippet is not working that well:

long seconds = lastRefreshPoint.until(systemTime, ChronoUnit.SECONDS);

This gives me the Exception:

java.time.temporal.UnsupportedTemporalTypeException: Unsupported unit: Minutes

I cant really find any other way to do this on the Internet. It would be nice if you could help me!

Thanks in advance


Solution

  • Okay, here my comment as answer together with some details about the reasons of the behaviour observed.

    Summarizing:

    This does not make any sense since a calendar date does not know anything about hours, minutes or seconds. The lowest supported unit must be the day. See also the API of Java-8-class LocalDate:

    If the unit is a ChronoUnit then the query is implemented here. The supported units are: •DAYS •WEEKS •MONTHS •YEARS •DECADES •CENTURIES •MILLENNIA •ERAS All other ChronoUnit instances will return false.

    Reasons:

    While someone can imagine to implement the difference in seconds between two connecting days as 86400 seconds (ignoring zone effects or leap seconds), it would not be a good idea. If the API designers had decided to support the between-arithmetic then they should also have decided to support adding of seconds to a date. But here the problem starts:

    date + 86400 secs = next date

    But what is date + 123 secs???

    The support for units more precise than a day in the class LocalDate would cause inconsistencies which cannot be cured.