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

1.9k views Asked by At

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)
2

There are 2 answers

0
azro On BEST ANSWER

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
1
Sweeper On

Note that LocalDate has not time component, and LocalTime has no date component. So your code is trying to calculate the number of hours between 2000-04-30 (with no time specified), and the current local time (with no date specified). See the problem?

What you probably meant is,

How many hours are there, between today at the current local time, and 2000-04-30 at the start of that day (or some other time that day)?

This calculation needs two "date+time"s, not one date and one time. We represent that with LocalDateTime.

long noOfHours = startDate.atStartOfDay().until(LocalDateTime.now(), ChronoUnit.HOURS);

Note LocalDateTime.now() and atStartOfDay, which returns LocalDateTimes.

If you want to use another time at 2000-04-30, use startDate.atTime(...), or create a LocalDateTime in the first place, e.g.

LocalDateTime startDate =  LocalDateTime.of(2000, 4, 30, 12, 30);