我写了一个方法来计算两个日期之间的差异。
这是方法:
/**
* Method to calculate time Difference between to Times Strings
*
* @param time1 The Current Time Time
* @param time2 Item Start Time
* @param item the Item should to be played
* @return Difference between Two Times as Seconds
*/
public static long timeDifference(String time1, String time2, Item item) {
// get the current Calendar Instance
Calendar now = Calendar.getInstance();
// calculate the days Difference between the Item Start Day and the current Day
int daysToAdd=0;
if(RestOperations.dayoffWeek<item.getDay()){
daysToAdd= (RestOperations.dayoffWeek-item.getDay()) * (-1);
}
else{
daysToAdd = 7-(RestOperations.dayoffWeek-item.getDay());
}
// parse the passed Times Strings to Date Objects
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Date date1 = null;
Date date2 = null;
try {
date1 = format.parse(time1);
date2 = format.parse(time2);
} catch (ParseException e) {
e.printStackTrace();
}
// set the Current Time to the current Calendar instance
now.setTime(date1);
// create Date for the Item
Calendar itemDate = Calendar.getInstance();
// set the Item Start Time to the Item Calendar Instance
itemDate.setTime(date2);
// add the Days Difference to the Item Calendar Insatnce to determinate the Start Date of the Item
itemDate.add(Calendar.DAY_OF_MONTH, daysToAdd);
// get Difference between the both Calendar Instances to determinate how much Seconds must the Thread be stopped
long difference = itemDate.getTimeInMillis()-now.getTimeInMillis();
/* if (date1 != null & date2 != null) {
difference = (int) (date2.getTime() - date1.getTime());
}*/
// start for debugging!
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
int sec = now.get(Calendar.SECOND);
int hour2 = itemDate.get(Calendar.HOUR_OF_DAY);
int minute2 = itemDate.get(Calendar.MINUTE);
int sec2 = itemDate.get(Calendar.SECOND);
String currDate = now.get(Calendar.YEAR)+"-"+now.get(Calendar.MONTH)+"-"+now.get(Calendar.DAY_OF_MONTH)+" "+hour + ":" + minute + ":" + sec;
String itDate = itemDate.get(Calendar.YEAR)+"-"+itemDate.get(Calendar.MONTH)+"-"+itemDate.get(Calendar.DAY_OF_MONTH)+" "+hour2 + ":" + minute2 + ":" + sec2;
Log.i("CurDate: ", currDate);
Log.i("ItemStartDate: ", itDate);
Log.i("difff: ", difference+"");
// end of debugging
return difference;
}
当我为此示例运行此方法时:
duration = Utility.timeDifference("11:8:56","07:04:43",6);
我得到年份= 1970年,月份= 0且持续时间为负数(<0)
因此,为了便于说明,第一个参数对应于当前时间。第二个参数对应于项目应该开始播放而第三个参数对应于项目应该开始播放的星期几。
在上面的代码中,我尝试执行以下操作:
第一个参数应转换为当前日期:20-11-2015 11:08:56。
第二个参数应使用第三个参数转换为当前日期:21-11-2015 07:04:43。
有人可以告诉我哪里可能是错误?