Solved

Compute number of months between two dates

Posted on 2007-11-22
5
5,728 Views
Last Modified: 2013-12-29
Hello,

I need to compute the number of months between two dates.
I have 4 variables :
int month1, year1, month2, year2;

for example for respectively 12, 1991, 10, 1991
It must give me 3

Thank you for any help.
0
Comment
Question by:matthew016
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
5 Comments
 
LVL 92

Accepted Solution

by:
objects earned 250 total points
ID: 20333349
be something like:

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);
}

0
 
LVL 4

Assisted Solution

by:jcoombes
jcoombes earned 250 total points
ID: 20333357
Can't you just:

1. Compute the number of years difference, by subtracting the larger year from the smaller year.
2. Multiply this value by 12 and store it.
3.  Compute the number of months difference between the months fields (in the example this would be 12 - 10 = 2)
4.  Add the stored month value to the value computed in 3.

I would have thought that the correct answer for the two dates you've posted is 2, BTW not 3?

Cheers


JC


0
 
LVL 13

Expert Comment

by:Bart Cremers
ID: 20333366
monthDiff(getDate(1992, 10), getDate(1991, 12)));

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);
}

Open in new window

0
 
LVL 2

Expert Comment

by:Ronald112197
ID: 21076568
well, I guess all of the above works, but why make life so difficult?
Just compute the "total number of months" for each date and subtract them from each other... then add one to include both the first and the last month.

Like this:
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...

Open in new window

0
 
LVL 2

Expert Comment

by:Ronald112197
ID: 21076586
btw... I just now realized what the accepted solution above does....
It performs really badly and uses recursion for no obvious reason...(it's not like some years have more months than others, right?)  You probably won't do that, but if you compute the months between October 1500 and December 2500, it will take at least 5000 times (!) longer (!) than my suggestion and use a LOT of memory in the process... (several megabytes)

Oh yes... AND it returns incorrect results if the two dates are not in the same year... (one month missing) which just shows that it's much too complex for the problem at hand...

P.S.: Just tried this just for fun: For a timespan of more than ~5500 years, you even get an OutOfMemory problem... (or rather a StackOverflowError because this does 5500 nested method calls!)...
0

Featured Post

Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Suggested Courses

623 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question