Calculation of hours with Java 8

Asked

Viewed 1,930 times

2

I was doing some tests with Java 8, and I was trying to calculate the difference between times of two dates. I did it in three ways, but I don’t know which one would be the right one and I’d like your help.

 LocalDateTime t1 = LocalDateTime.of(2014, Month.NOVEMBER, 25, 8, 23);  
 LocalDateTime t2 = LocalDateTime.of(2014, Month.NOVEMBER, 25, 10, 23);  

 long horas = ChronoUnit.HOURS.between(t1, t2);  
 System.out.println(horas);  

 long horas2 = t1.until(t2, ChronoUnit.HOURS);  
 System.out.println(horas2);  

 long horas3 = Duration.between(t1, t2).toHours();  
 System.out.println(horas3);  

According to the documentation, the horas2 and the horas3 are equivalent, however, I was in doubt the first way. It is correct?

  • Just for the sake of knowledge, the method itself HOURS.between(t1, t2) is equivalent to t1.until(t2, ChronoUnit.HOURS).

1 answer

2


It seems to me that the three forms are correct and are equivalent.

However, it seems to me that all three will fail if there are daylight saving or time zone changes.

  • Yes, it seems that the LocalDateTime has no support for time-zone, so... I ran the code snippet and here it gave the same result. Difference always two hours.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.