Search code examples
javatimedurationlocaltimeminute

How to have minutes between two times?


I have two times and I want to get the difference in minutes.

Ex:

I have this:

09:11:30;09:15:22;

And I want to achieve this:

3 min passed

Note that the 9:15:22 is not 9:15:30 so 4 minutes are not passed already.


Solution

  • As with any date/time question, get your data into the best representable container, in this case, that would be LocalTime

    DateTimeFormatter pattern = DateTimeFormatter.ofPattern("HH:mm:ss", Locale.ENGLISH);
    LocalTime from = LocalTime.parse("09:11:30", pattern);
    LocalTime to = LocalTime.parse("09:15:22", pattern);
    

    From there you can simply use the API to do the work for you, in this case, making use of Duration...

    Duration duration = Duration.between(from, to);
    System.out.println(duration.toMinutes());
    

    Which prints 3 (pretty sure you can add the rest of the formatting)

    For more information, you could have a look at the Date/Time tutorials