Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate difference between two hour's strings

I have a string that contain certain hour ex. 14:34, and now I want to calculate the difference between the current hour ex. 21:36-14:34=7 hours 2 minutes (or something like that.) Can someone explain me how can I do that?

like image 328
Darko Petkovski Avatar asked Jun 18 '14 23:06

Darko Petkovski


2 Answers

It's very easy: You need to separate the string in terms you can add or substract:

   String timeString1="12:34";
   String timeString2="06:31"; 

   String[] fractions1=timeString1.split(":");
   String[] fractions2=timeString2.split(":");
   Integer hours1=Integer.parseInt(fractions1[0]);
   Integer hours2=Integer.parseInt(fractions2[0]);
   Integer minutes1=Integer.parseInt(fractions1[1]);
   Integer minutes2=Integer.parseInt(fractions2[1]);      
   int hourDiff=hours1-hours2;
   int minutesDiff=minutes1-minutes2;
   if (minutesDiff < 0) {
       minutesDiff = 60 + minutesDiff;
       hourDiff--;
   }
   if (hourDiff < 0) {
       hourDiff = 24 + hourDiff ;
   }
   System.out.println("There are " + hourDiff + " and " + minutesDiff + " of difference");

UPDATE:

I'm rereading my answer and I'm surprised is not downvoted. My fault. I wrote it without any IDE check. So, the answer should be minutes1 and 2 for the minutesDiff and obviously and a check to carry the hour difference if the rest of minutes is negative, making minutes (60+minutesDiff). If minutes is negative, rest another hour to the hourDiff. If hours become negative too, make it (24+hourDiff). Now is fixed.

For the sake of fastness, I'm using a custom function. For the sake of scalability, read Nikola Despotoski answer and complete it with this:

System.out.print(Hours.hoursBetween(dt1, dt2).getHours() % 24 + " hours, ");
System.out.println(Minutes.minutesBetween(dt1, dt2).getMinutes() % 60 + " minutes, ");
like image 178
Alex Avatar answered Sep 30 '22 01:09

Alex


I would start by using the .split method to get the string into its two components (minutes and hours) then I would convert both times into minutes by mutliplying the hours by 60 and then adding the minutes

String s = "14:34";
String[] sArr = s.split(",");
int time = Integer.parseInt(sArr[0]);
time *= 60;
int time2 = Integer.parseInt(sArr[1]);
time = time + time2;

do this for both strings and then subtract one from the other. You can convert back to normal time by using something like this

int hours = 60/time;
int minutes = 60%time;

The answer labeled as correct will not work. It does not account for if the first time is for example 3:17 and the second is 2:25. You end up with 1 hour and -8 minutes!

like image 44
a_river_in_canada Avatar answered Sep 30 '22 00:09

a_river_in_canada