我想计算两个日期之间的日期,但是某些情况下堆栈溢出的某些解决方案对我不起作用,例如:当结束日期比开始日期晚几天后开始
答案 0 :(得分:-2)
因此,通过此代码,我解决了所有问题,并且现在和以后都可以正常工作:)
private String getDifferenceBtwDates (String dateDebut, String dateFin){
if (StringUtility.isEmptyOrNull(dateDebut) || StringUtility.isEmptyOrNull(dateFin)){
return "0" ;
}else {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
Date startDate = null;
Date finDate = null;
try {
startDate = sdf.parse(dateDebut);
finDate = sdf.parse(dateFin);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();
calendar1.setTime(startDate);
calendar2.setTime(finDate);
/*
* Use getTimeInMillis() method to get the Calendar's time value in
* milliseconds. This method returns the current time as UTC
* milliseconds from the epoch
*/
long miliSecondForDate1 = calendar1.getTimeInMillis();
long miliSecondForDate2 = calendar2.getTimeInMillis();
// Calculate the difference in millisecond between two dates
long diffInMilis = miliSecondForDate2 - miliSecondForDate1;
/*
* Now we have difference between two date in form of millsecond we can
* easily convert it Minute / Hour / Days by dividing the difference
* with appropriate value. 1 Second : 1000 milisecond 1 Hour : 60 * 1000
* millisecond 1 Day : 24 * 60 * 1000 milisecond
*/
long diffInDays = diffInMilis / (24 * 60 * 60 * 1000);
return "" + diffInDays ;
}
}