Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Duration between exception

Tags:

java

time

java-8

I use the java Duration between method to calcul a duration between to a LocalTime and LocalDateTime it's work when I put the localTime as the first argument of the method but when I reversed the order it gave an exception DateTimeException :

This work fine :

 LocalTime t1 = LocalTime.now();
 LocalDateTime t2 = LocalDateTime.now();
 System.out.println(Duration.between(t1, t2));

When I reversed the agrs it gave me an exception :

 LocalTime t1 = LocalTime.now();
 LocalDateTime t2 = LocalDateTime.now();
 System.out.println(Duration.between(t2, t1));

Exception in thread "main" java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: 16:32:18.553 of type java.time.LocalTime

can someone explain why I get this exception thanks for any help :=)

like image 604
e2rabi Avatar asked Dec 22 '22 21:12

e2rabi


1 Answers

From the docs: Duration between

If the objects are of different types, then the duration is calculated based on the type of the first object. For example, if the first argument is a LocalTime then the second argument is converted to a LocalTime.

So basically, the error is thrown because you can't cast a LocalTime object into a LocalDateTime, the date information is not included in the LocalTime.

like image 54
reptilicus Avatar answered Jan 01 '23 15:01

reptilicus