简体   繁体   English

在java中计算两次差异的最佳方法是什么?

[英]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. 为此,所有计算“看起来”都有效,但例如10.18和09.35之间的差异是1小时23分钟或总共83分钟。 My program seems to show 43 mins. 我的节目似乎显示43分钟。

I have tried other ways but still cannot get it working, any ideas? 我尝试了其他方法,但仍然无法让它工作,任何想法?

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

Have a look at the Joda library. 看看Joda图书馆。

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? 分钟不是剩余的小时数除以100,而是60.这就是那段代码应该做的吗?

Also, you might be better off just using a Calendar object. 此外,您可能最好只使用Calendar对象。

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. 然后使用它的getTime方法。 It will give you the time in milliseconds(long). 它会给你时间,以毫秒(长)为单位。 Then subtract the times. 然后减去时间。 and then convert them to minutes and hours. 然后将它们转换为分钟和小时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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