从两个时间选择器获得总小时数的最佳方法是什么?我有两个不同的时间选择器,每次选择器有时间和超时。如果两个时间选择器已经填满,则下面的编码工作正常,但如果只填充一个时间选择器则不起作用。任何建议都会非常感激。
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
Date dateb = null; //time in
Date datec = null; //time out
Date dateb1 = null; //time in1
Date datec1 = null; // time out2
try {
dateb = format.parse(b);
datec = format.parse(c);
long difference = datec.getTime() - dateb.getTime();
int minutes = (int) ((difference / (1000 * 60)) % 60);
int hours = (int) ((difference / (1000 * 60 * 60)) % 24) - 1;
editTextH1.setText((hours + ":" + minutes));
} catch (Exception e) {
System.err.println("ouch!");
}
try {
dateb1 = format.parse(d);
datec1 = format.parse(e1);
long difference1 = datec1.getTime() - dateb1.getTime();
int minutes1 = (int) ((difference1 / (1000 * 60)) % 60);
int hours1 = (int) ((difference1 / (1000 * 60 * 60)) % 24) - 1;
editTextH2.setText((hours1 + ":" + minutes1));
} catch (Exception e) {
System.err.println("ouch!");
}
try {
long dateb_sum = dateb.getTime() + dateb1.getTime();
long datec_sum = datec.getTime() + datec1.getTime();
long difference4 = datec_sum - dateb_sum;
int minutes4 = (int) ((difference4 / (1000 * 60)) % 60);
int hours4 = (int) ((difference4 / (1000 * 60 * 60)) % 24) - 1;
editText8.setText((hours4 + ":" + minutes4));
}catch(Exception e)
{
System.err.println("ouch!");
}
editText8将总结editTextH1和editTextH2的总数...如果这两个时间选择器已填满,一切正常。但是现在我想设置editText8也会获得值,即使填充了一次选择器(当只有一个时间选择器被填充时,editText8 = editTextH1的值)...请帮助..我一直在坚持这里超过两天......
答案 0 :(得分:1)
如果移动变量以将差异保持在外部范围内,则不需要尝试让它们添加它们。
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
long difference = 0;
long difference1 = 0;
try {
Date dateb = format.parse(b); //time in
Date datec = format.parse(c); //time out
difference = datec.getTime() - dateb.getTime();
int minutes = (int) ((difference / (1000 * 60)) % 60);
int hours = (int) ((difference / (1000 * 60 * 60)) % 24) - 1;
editTextH1.setText((hours + ":" + minutes));
} catch (Exception e) {
System.err.println("ouch!");
}
try {
Date dateb1 = format.parse(d);
Date datec1 = format.parse(e1);
long difference1 = datec1.getTime() - dateb1.getTime();
int minutes1 = (int) ((difference1 / (1000 * 60)) % 60);
int hours1 = (int) ((difference1 / (1000 * 60 * 60)) % 24) - 1;
editTextH2.setText((hours1 + ":" + minutes1));
} catch (Exception e) {
System.err.println("ouch!");
}
long difference4 = difference + difference1;
int minutes4 = (int) ((difference4 / (1000 * 60)) % 60);
int hours4 = (int) ((difference4 / (1000 * 60 * 60)) % 24) - 1;
editText8.setText((hours4 + ":" + minutes4));
我也会像How to find the duration of difference between two dates in java?
那样使用TimeUnit.MILLISECONDS.toMinutes(difference)
和TimeUnit.MILLISECONDS.toHours(difference)