简体   繁体   中英

Best way to calculate difference between two times in 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?

使用DateFormat (可能是SimpleDateFormat )对象来解析你的String,不要尝试使用parseDouble() (用于解析单个数字,而不是时间)。

Have a look at the Joda library.

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

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.

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();
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)); 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM