Search code examples
javajava-timedate-differencechronounit

Why ChronoUnit.HOURS.between() is NOT working?


I was trying to get the hours between two local dates. And I used the code below :

 LocalDate startDate =  LocalDate.of(2000, 4, 30);

    long noOfHours = startDate.until(LocalTime.now(), ChronoUnit.HOURS);
    
    System.out.println(noOfHours);

I am having the error below :

Exception in thread "main" java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: 13:44:53.095819600 of type java.time.LocalTime
    at java.base/java.time.LocalDate.from(LocalDate.java:397)
    at java.base/java.time.LocalDate.until(LocalDate.java:1645)
    at BirthDay.App.main(App.java:36)

Solution

  • Error 1

    As the exception states : you need coherent bound values, LocalTime has no day/month/year composants to be compared to a LocalDate

    LocalDate startDate = LocalDate.of(2000, 4, 30);
    long noOfHours = startDate.until(LocalTime.now(), ChronoUnit.HOURS);
    // >> DateTimeException: Unable to obtain LocalDate from java.time.LocalTime
    

    Error 2

    Also you need composants that have the unit required by your ChronoUnit, using 2 LocalDate won't work with HOURS as they have none.

    LocalDate startDate = LocalDate.of(2000, 4, 30);
    long noOfHours = startDate.until(LocalDate.now(), ChronoUnit.HOURS);
    // >> UnsupportedTemporalTypeException: Unsupported unit: Hours
    

    Use LocalDateTime for that, to be coherent for both bounds and for unit time

    LocalDateTime startDate = LocalDateTime.of(2000, 4, 30, 0, 0, 0);
    long noOfHours = startDate.until(LocalDateTime.now(), ChronoUnit.HOURS);
    System.out.println(noOfHours); // 185793