0

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.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
José Nobre
  • 4,407
  • 6
  • 20
  • 40
  • What you have tried till now ? You can convert both input time to seconds , get the difference and then divide by 60 to get difference in minutes. As you are interested only in minutes, you can define 'diffInMin' variable as 'int' – sauumum Jun 06 '18 at 19:40
  • Two times or two durations? Your title conflicts with the body of your Question. – Basil Bourque Jun 07 '18 at 00:06

2 Answers2

9

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

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
-1
String time1 = "09:11:30";
String time2 = "09:15:22";

SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Date date1 = format.parse(time1);
Date date2 = format.parse(time2);
long difference = date2.getTime() - date1.getTime(); 
long difInMinute = (difference/1000)/60;
System.out.println(difInMinute+" min passed");

Credits: Uros K

Sundeep
  • 452
  • 2
  • 12
  • 2
    Thanks for wanting to contribute. Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. – Ole V.V. Jun 06 '18 at 20:34
  • OK Thanks, I'll keep in mind – Sundeep Jun 07 '18 at 02:26