如何根据用户输入计算java中的时差?以下是工作代码段。
@Override
public void onTimeSet(TimePicker view,int hourofDay, int minute)
{
if (flag == FLAG_START_DATE) {
start.setText(Integer.toString(hourofDay) + "." + Integer.toString(minute));
b=start.getText().toString();
} else if (flag == FLAG_END_DATE) {
end.setText(Integer.toString(hourofDay) + "." + Integer.toString(minute));
c=end.getText().toString();
//endTime=hourofDay;
}
SimpleDateFormat format= new SimpleDateFormat("HH:mm");
Date date1=format.parse(b);
Date date2=format.parse(c);
long difference=date2.getTime()-date1.getTime();
editText.setText(""+difference);
}
}
错误:未报告的异常ParseException;必须被抓住或宣布被抛出
答案 0 :(得分:1)
从您的错误中,它是由ParseException导致的,您可以通过添加try和catch来修复它。
try{
// do your calculation here
// for your case will be:
SimpleDateFormat format= new SimpleDateFormat("HH:mm");
Date date1=format.parse(b);
Date date2=format.parse(c);
long difference=date2.getTime()-date1.getTime();
editText.setText(""+difference);
}
catch(ParseException ex){
System.err.println("ouch!");
}
然后,您可以将总的不同毫秒转换为小时,分钟,秒等。
int seconds = (int) (difference/ 1000) % 60 ;
int minutes = (int) ((difference/ (1000*60)) % 60);
int hours = (int) ((difference/ (1000*60*60)) % 24);
//etc...
答案 1 :(得分:1)
您需要捕获可能从parse()
调用中抛出的ParseException:
try {
SimpleDateFormat format= new SimpleDateFormat("HH:mm");
Date date1=format.parse(b);
Date date2=format.parse(c);
long difference=date2.getTime()-date1.getTime();
editText.setText(""+difference);
} catch (ParseException pe) {
editText.setText("Failed to parse dates"); // or whatever you want
}
答案 2 :(得分:1)
尝试将.
分隔符替换为:
分隔符以获取时间,并且休息效果很酷
if (flag == FLAG_START_DATE) {
start.setText(Integer.toString(hourofDay) + ":" + Integer.toString(minute));
b=start.getText().toString();
} else if (flag == FLAG_END_DATE) {
end.setText(Integer.toString(hourofDay) + ":" + Integer.toString(minute));
c=end.getText().toString();
//endTime=hourofDay;
}