Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to calculate difference between two times in java?

Tags:

java

I have two times in an array and I need to calculate the difference between both of these. I have converted the hours into mins, then added the remaining mins. This gives me the total minutes overall, once I did this for both I simply minus one total mins from the other. Then converted them back to hours and minutes.

double no1 = Double.parseDouble(array[i][4]);
int time1_calc = (int) (no1 * 100); //Remove decimal point
int time1hours = (time1_calc) / 100;
int time1mins = (time1_calc) % 100;
int time1HM = time1hours*60;
int time1_total = time1HM + time1mins;

The above code is used for the second time, I then use:

int total = time2_total - time1_total;

For this all the calculations "look" to work, but for example the difference between 10.18 and 09.35 is 1 hour 23 mins or 83 mins in total. My program seems to show 43 mins.

I have tried other ways but still cannot get it working, any ideas?

like image 655
Elliott Avatar asked Dec 10 '25 04:12

Elliott


1 Answers

Use a DateFormat (probably SimpleDateFormat) object to parse your String and don't try to use parseDouble() (that's for parsing a single number, which a time is not).

like image 155
Joachim Sauer Avatar answered Dec 12 '25 17:12

Joachim Sauer