I have this code that works for me and is simpler:
public static String dhmsDifference(Date d1, Date d2) { long diff = d2.getTime() - d1.getTime(); long diffSeconds = diff / 1000 % 60; long diffMinutes = diff / (60 * 1000) % 60; long diffHours = diff / (60 * 60 * 1000) % 24; long diffDays = diff / (24 * 60 * 60 * 1000); String difference=Long.toString(diffDays)+":"+String.format("%02d", diffHours)+":"+String.format("%02d", diffMinutes)+":"+String.format("%02d", diffSeconds); return difference; }
It returns a string, but you can easily adapt it to your code, I think.
For a month and years, I used a calendar (added to my code):
Calendar cal1 = Calendar.getInstance(); Calendar cal2 = Calendar.getInstance(); cal1.setTime(d1); cal2.setTime(d2); long months = cal2.get(Calendar.MONTH)-cal1.get(Calendar.MONTH); long years = cal2.get(Calendar.YEAR)-cal1.get(Calendar.YEAR); long weeks = cal2.get(Calendar.WEEK_OF_YEAR)-cal1.get(Calendar.WEEK_OF_YEAR);
You will need to add magic if the year changes, but this is an idea.
EDIT: Does some tests with this more complete code, please:
public static String ymwdhmsDifference(Date d1, Date d2) { long diff = d2.getTime() - d1.getTime(); long diffSeconds = diff / 1000 % 60; long diffMinutes = diff / (60 * 1000) % 60; long diffHours = diff / (60 * 60 * 1000) % 24; long totalDiffDays = diff / (24 * 60 * 60 * 1000); long diffDays = totalDiffDays % 7; long diffWeeks = totalDiffDays/7; // Full weeks are simply days / 7. diffDays = diffDays % 7; // now we get the remaining days. Calendar cal1 = Calendar.getInstance(); Calendar cal2 = Calendar.getInstance(); cal1.setTime(d1); cal2.setTime(d2); long totalDiffYears = cal2.get(Calendar.YEAR)-cal1.get(Calendar.YEAR); long totalDiffMonths = Math.max(totalDiffYears*12+cal2.get(Calendar.MONTH)-cal1.get(Calendar.MONTH)-1,0); long diffYears = totalDiffMonths / 12; // remaining full months long diffMonths = totalDiffMonths % 12; // now we have to count how many weeks those full months represent, to substract them from the number of weeks... Calendar cal3 = Calendar.getInstance(); cal3.setTime(d1); int month = cal1.get(Calendar.MONTH)+1, year = cal1.get(Calendar.YEAR), monthDays=0; for (int m=0;m<totalDiffMonths;m++) { cal3.set(Calendar.MONTH, month++); monthDays+=cal3.getActualMaximum(Calendar.DAY_OF_MONTH); if (month>=12) { month = 0; year++; cal3.set(Calendar.YEAR, year); } } diffWeeks-=monthDays/7; // Note that the number of weeks can be greater than 4 because they are part of non full months. String difference="Y: "+Long.toString(diffYears)+" M: "+Long.toString(diffMonths)+" W: "+Long.toString(diffWeeks)+" D: "+Long.toString(diffDays)+" H: "+String.format("%02d", diffHours)+" M: "+String.format("%02d", diffMinutes)+" S: "+String.format("%02d", diffSeconds); return difference; }
source share