[英]Calculate time difference between two EditText
I have seen almost similar questions about this but my wont work as I want. 我已经看到了几乎类似的问题,但我不会按照我的意愿工作。 Not at all in fact.
实际上完全没有。
So I have been trying to calculate the time difference between two timestamps that I set with a TimePicker to two EditTexts. 所以我一直在尝试计算使用TimePicker设置的两个时间戳与两个EditTexts之间的时差。
Here is the code I dont get to work: 这是我不能工作的代码:
public void calcTime() throws Exception{
String startTime = startworkFrom.getText().toString();
String endTime = startworkTo.getText().toString();
DateFormat format = new SimpleDateFormat("hh:mm a");
Date time_1 = format.parse(startTime);
Date time_2 = format.parse(endTime);
long timeDiff = time_2.getTime() - time_1.getTime();
System.out.println("Time difference" + timeDiff);
}
What is missing in the code? 代码中缺少什么?
UPDATE UPDATE
I found the problem that is this line: 我找到了这一行的问题:
DateFormat format = new SimpleDateFormat("hh:mm a");
DateFormat format = new SimpleDateFormat(“hh:mm a”);
If I delete the ' a '. 如果我删除' a '。 Also the value is really high.
价值也很高。 If I set 12:00 to 13:00 the difference should be 1.But I get a really huge value here.
如果我将12:00设置为13:00,差异应该是1.但是我在这里获得了非常大的价值。 I will be using
我会用的
The only problem now is if I start to work late at night and then stop working in the morning i will get a negative value but I guess there is a fix for that for another topic.
现在唯一的问题是,如果我开始深夜工作,然后在早上停止工作,我会得到一个负值,但我想有另一个主题的解决方案。
This should do it 这应该做到这一点
String neg = "-";
long timeDiff;
if(timeDiff.contains(neg)){
timeDiff = time_1.getTime() - time_2.getTime(); }
else{ timeDiff =
time_2.getTime() - time_1.getTime(); }
System.out.println("Time difference" + timeDiff);
A solution to the negative values is to use the Math library. 负值的解决方案是使用Math库。 I did like this:
我喜欢这样:
String a =""+Math.abs(diff/(60*60*1000)%24);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.