我试图获得两个用户设置时间之间的差异。我非常接近让这个工作,但我无法从一天到另一天得到差异。例如,如果开始时间是晚上11点,结束时间是凌晨1点,那么它将说21:00,因为它不知道一天变化后该做什么。请帮助,继承我的时间选择码。
// Creates Simple Date Format//
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
// Parses StartTime 24 Hour Format//
try {
if (military_start_time == null) {
} else {
date1 = sdf.parse(military_start_time);
}
} catch (ParseException e) {
e.printStackTrace();
}
// Parses EndTime 24 Hour Format//
try {
if (military_end_time == null) {
} else {
date2 = sdf.parse(military_end_time);
}
} catch (ParseException e) {
e.printStackTrace();
}
// If End Time Equals Null Do Nothing//
if (military_end_time != null) {
// If Start Time Equals Null Do Nothing//
if (military_start_time != null) {
// Subtracts Two Times In 24 Hour Format And Then Puts It Into 12 Hour Format//
long differance = date2.getTime() - date1.getTime();
int days = (int) (differance / (1000*60*60*24));
int hours = (int) ((differance - (1000*60*60*24*days)) / (1000*60*60));
int min = (int) (differance - (1000*60*60*24*days) - (1000*60*60*hours)) / (1000*60);
String diffTime = (hours<0 ? "0" + -hours : hours) + ":" + (min < 10 ? "0" + min : min);
// Set Time Differance//
totaltime.setText(diffTime);
}
}
}
答案 0 :(得分:0)
您可以使用Joda-Time库。见here
答案 1 :(得分:0)
试试这个:
long diff = date2.getTime() - date1.getTime();
long seconds = TimeUnit.MILLISECONDS.toSeconds(diff);
long minutes = TimeUnit.MILLISECONDS.toMinutes(diff);
long hours = TimeUnit.MILLISECONDS.toHours(diff);
long days = TimeUnit.MILLISECONDS.toDays(diff);
答案 2 :(得分:0)
我有自己的客户方法,我长期使用,你可以使用它。它肯定适合你。下面是代码 -
public static String getTimeDifferance(String startTime,String endTime){
try{
Date time1 = new SimpleDateFormat("HH:mm:ss").parse(endTime);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(time1);
Date time2 = new SimpleDateFormat("HH:mm:ss").parse(startTime);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(time2);
Date x = calendar1.getTime();
Date xy = calendar2.getTime();
long diff = x.getTime() - xy.getTime();
int diffMinutes = (int) (diff / (60 * 1000));
int diffHours = diffMinutes / 60;
System.out.println("diff hours" + diffHours);
if(diffMinutes>59){
diffMinutes = diffMinutes%60;
}
String totalDiff = diffHours+":"+diffMinutes+":00";
return totalDiff;
}
catch(Exception e){
e.printStackTrace();
}
return "";
}
希望我对你有所帮助。一切顺利!!
<强> EDITED 强>
将您的代码更新为 -
if (military_start_time != null) {
String timeDiff = getTimeDifferance(military_start_time,military_end_time);
totaltime.setText(timeDiff);
}