int months(int month1, year1, int month2, int year2)
{
if (year1>year2)
{
return months(month2, year2, month1, year1);
}
else if (year1==year2)
{
return Math.max(month1 - month2) + 1;
}
return (12 - month1) + months(1, year1+1, month2, year2);
}
private static Date getDate(int year, int month) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month);
return cal.getTime();
}
private static int monthDiff(Date one, Date two) {
Calendar calFirst = Calendar.getInstance();
Calendar calLast = Calendar.getInstance();
if (!one.after(two)) {
calFirst.setTime(one);
calLast.setTime(two);
} else {
calFirst.setTime(two);
calLast.setTime(one);
}
int diff = 0;
while (!equalMonthAndYear(calFirst, calLast)) {
diff++;
calFirst.add(Calendar.MONTH, 1);
}
return diff;
}
private static boolean equalMonthAndYear(Calendar first, Calendar last) {
return first.get(Calendar.YEAR) == last.get(Calendar.YEAR)
&& first.get(Calendar.MONTH) == last.get(Calendar.MONTH);
}
public static int calDiff(int year1, int month1, int year2, int month2) {
int monthsDiff = (year1 * 12 + month1) - (year2 * 12 + month2);
return Math.abs(monthsDiff) + 1;
}
// or even:
int diff = Math.abs((year1 * 12 + month1) - (year2 * 12 + month2)) + 1;
A bit more compact than the solutions above, but at least as readable IMHO...
Cheers...
If you are experiencing a similar issue, please ask a related question
Title | # Comments | Views | Activity |
---|---|---|---|
@SBGen Method | 3 | 38 | |
what is the difference between "sudo su" and "su - root" | 6 | 106 | |
How to monitor the number of connections/threads being utilized on Tomcat 6.0 | 8 | 57 | |
eclipse shortcuts | 9 | 45 |
Join the community of 500,000 technology professionals and ask your questions.
Connect with top rated Experts
25 Experts available now in Live!