Tutorial :Best way to calculate difference between two times in java?



Question:

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?


Solution:1

Calendar time1 =  Calendar.getInstance();  // assign time1 date from your array    Calendar time2 =  Calendar.getInstance();  // assign time2 date from your array    long diff = time1.getTimeInMillis() - time2.getTimeInMillis();  


Solution:2

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).


Solution:3

int time1mins = (time1_calc) % 100;  

Minutes are not the remainder of hours divided by 100, but by 60. Is that what that bit of code is meant to be doing?

Also, you might be better off just using a Calendar object.


Solution:4

Have a look at the Joda library.

If you want to do it by yourself, then your code looks correct to me.


Solution:5

Use the Date Object. Then Use its getTime method. It will give you the time in milliseconds(long). Then subtract the times. and then convert them to minutes and hours.


Solution:6

long timeMillis = System.currentTimeMillis();  System.out.println("Current time in millis:"+timeMillis);       Thread.sleep(1200);     long timeMillis2 = System.currentTimeMillis();  System.out.println("Current time in millis:"+timeMillis2);  System.out.println("Difference betwwen 2 times:"+(timeMillis2-timeMillis));   

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »