Search code examples
javadatetimedifferenceduration

Duration.between() doesn't work the way I want to


I want the exact duration in hours between dates. The between-method seems to only consider the difference in whole hours. Why is that and what can I do/use instead?

Duration dur = Duration.between(
    LocalDateTime.of(2020, 5, 20, 12, 00), LocalDateTime.of(2020, 5, 20, 16, 45));

float durH = dur.toHours(); 

System.out.println(durH);

This code gives me 4.0 but what I want is 4.75.


Solution

  • This works just fine.

    double durH = dur.toMinutes()/60.;
    // or
    double durH = dur.toMinutes()/60.f;
    
    System.out.println(durH);
    

    prints

    4.75