50

I have two LocalTime objects:

LocalTime l1 = LocalTime.parse("02:53:40");
LocalTime l2 = LocalTime.parse("02:54:27");

How can I found different in minutes between them?

Bob
  • 10,427
  • 24
  • 63
  • 71
  • 1
    Note that all existing answers assume the times to be on the same calendar day. That is, the difference between 23:58 and 00:03 would be given as -1435 minutes, not 5 minutes as one might expect. (This is probably by design, because a LocalTime does not know about the length of the respective day) – meriton Aug 14 '19 at 19:08

4 Answers4

59

Use until or between, as described by the api

import java.time.LocalTime;
import static java.time.temporal.ChronoUnit.MINUTES;

public class SO {
    public static void main(String[] args) {
        LocalTime l1 = LocalTime.parse("02:53:40");
        LocalTime l2 = LocalTime.parse("02:54:27");
        System.out.println(l1.until(l2, MINUTES));
        System.out.println(MINUTES.between(l1, l2));
    }
}

0
0

Yosef Weiner
  • 5,432
  • 1
  • 24
  • 37
46

Since Java 8 you can use Duration class. I think that gives the most elegant solution:

long elapsedMinutes = Duration.between(l1, l2).toMinutes();
nslxndr
  • 573
  • 5
  • 8
9

I do this with ChronoUnit

long minutesBetween = ChronoUnit.MINUTES.between(l1,l2);

Example

    LocalTime localTime=LocalTime.now();
    LocalTime localTimeAfter5Minutes=LocalTime.now().plusMinutes(5);
    Long minutesBetween=ChronoUnit.MINUTES.between(localTime,localTimeAfter5Minutes);
    System.out.println("Diffrence between time in munutes : "+minutesBetween);

Output

Diffrence between time in munutes : 5
Neeraj Jain
  • 7,643
  • 6
  • 34
  • 62
0

You could do this:

long dif = Math.abs (l1.getLocalMillis () - l2.getLocalMillis ());
TimeUnit.MINUTES.convert (dif, TimeUnit.MILLISECONDS);
Lev Kuznetsov
  • 3,520
  • 5
  • 20
  • 33